PostgreSQL guide · Forward geocoding

Geocode addresses in a PostgreSQL table.

Add coordinates to the customer, property or site addresses you already store. Rows are geocoded in batches outside the database, written back in one transaction, and only new or edited addresses are looked up again.

50,000 monthly credits on the Free plan, at up to 2 requests per second.

The examples use a customers table with an id primary key and a single-line address column. Replace those names with yours. You need psql, Python 3.9 or newer and a secret key from the dashboard.

1. Add columns for the result

Store the result next to the address. geocoded_at marks rows that are done, so a batch picks up only the rest. The trigger clears the result when an address changes, which puts the row back in the queue.

setup.sql
ALTER TABLE customers
  ADD COLUMN lat double precision,
  ADD COLUMN lon double precision,
  ADD COLUMN matched_address text,
  ADD COLUMN good_match boolean,
  ADD COLUMN geocoded_at timestamptz;

CREATE INDEX customers_to_geocode ON customers (id) WHERE geocoded_at IS NULL;

-- An edited address loses its old result and goes back in the queue.
CREATE FUNCTION customers_address_changed() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  NEW.lat := NULL;
  NEW.lon := NULL;
  NEW.matched_address := NULL;
  NEW.good_match := NULL;
  NEW.geocoded_at := NULL;
  RETURN NEW;
END
$$;

CREATE TRIGGER customers_address_changed
  BEFORE UPDATE OF address ON customers
  FOR EACH ROW WHEN (OLD.address IS DISTINCT FROM NEW.address)
  EXECUTE FUNCTION customers_address_changed();

2. Geocode a batch of rows

The batch script exports up to 1,000 pending rows with \copy, geocodes them with the CSV script from the bulk geocoding guide, then loads the results into a temporary table and updates the matching rows in one transaction. A row whose address was edited during the run is skipped and stays in the queue.

geocode_table.sh
#!/usr/bin/env bash
# Geocode one batch of customers without a result: bash geocode_table.sh
set -euo pipefail
: "${DATABASE_URL:?Set DATABASE_URL}" "${OPENGEOCODING_API_KEY:?Set OPENGEOCODING_API_KEY}"
batch=${BATCH_SIZE:-1000}
[[ $batch =~ ^[1-9][0-9]*$ ]] || { echo 'BATCH_SIZE must be a positive whole number' >&2; exit 1; }
here=$(cd "$(dirname "$0")" && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT

psql "$DATABASE_URL" -X -q -v ON_ERROR_STOP=1 -c "\copy (
  SELECT id, address FROM customers
  WHERE geocoded_at IS NULL AND btrim(address) <> ''
  ORDER BY id LIMIT $batch
) TO '$work/todo.csv' WITH (FORMAT csv, HEADER)"

status=0
python3 "$here/geocode_csv.py" "$work/todo.csv" "$work/done.csv" || status=$?

# Save the rows that finished even when the run stopped early: their credits are spent.
psql "$DATABASE_URL" -X -q -v ON_ERROR_STOP=1 <<SQL
BEGIN;
CREATE TEMP TABLE geocoded ON COMMIT DROP AS
  SELECT id, address, lat, lon, matched_address, good_match FROM customers WITH NO DATA;
\copy geocoded FROM '$work/done.csv' WITH (FORMAT csv, HEADER)
UPDATE customers c
SET lat = g.lat, lon = g.lon, matched_address = g.matched_address,
    good_match = g.good_match, geocoded_at = now()
FROM geocoded g
WHERE c.id = g.id AND c.address = g.address;
COMMIT;
SQL
exit "$status"

Save the CSV script as geocode_csv.py in the same directory:

geocode_csv.py
"""Geocode the "address" column of a CSV: python3 geocode_csv.py in.csv out.csv"""

import csv
import json
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from urllib.error import HTTPError
from urllib.request import Request, urlopen

API_URL = os.environ.get('OPENGEOCODING_API_URL', 'https://api.opengeocoding.com') + '/v1/search'
API_KEY = os.environ['OPENGEOCODING_API_KEY']
REQUESTS_PER_SECOND = int(os.environ.get('REQUESTS_PER_SECOND', '5'))  # your plan's limit


def search(address):
    for attempt in range(6):
        request = Request(
            API_URL,
            data=json.dumps({'addressString': address}).encode(),
            headers={'x-api-key': API_KEY, 'Content-Type': 'application/json'},
            method='POST',
        )
        try:
            with urlopen(request, timeout=30) as response:
                return json.load(response)
        except HTTPError as error:
            retry_after = error.headers.get('Retry-After')
            if error.code == 429 and retry_after:
                time.sleep(float(retry_after))
            elif error.code == 503:
                time.sleep(2**attempt)
            else:
                # 429 without Retry-After means the credits ran out.
                raise SystemExit(f'{error.code} for {address!r}: {error.read().decode()}')
    raise SystemExit(f'Gave up on {address!r}')


def geocode(row):
    # Each worker spends at least one second per row, so N workers stay under N requests/second.
    started = time.monotonic()
    result = search(row['address']) if row['address'].strip() else {}
    time.sleep(max(0, 1 - (time.monotonic() - started)))
    point = result.get('geoCoordinates', {})
    return {
        **row,
        'lat': point.get('lat', ''),
        'lon': point.get('lon', ''),
        'matched_address': result.get('displayName', ''),
        'good_match': result.get('goodMatch', False),
    }


with open(sys.argv[1], newline='', encoding='utf-8') as source:
    reader = csv.DictReader(source)
    rows = list(reader)
    columns = [*reader.fieldnames, 'lat', 'lon', 'matched_address', 'good_match']

with open(sys.argv[2], 'w', newline='', encoding='utf-8') as target:
    writer = csv.DictWriter(target, columns)
    writer.writeheader()
    with ThreadPoolExecutor(REQUESTS_PER_SECOND) as pool:
        for done, row in enumerate(pool.map(geocode, rows), 1):
            writer.writerow(row)
            print(f'\r{done}/{len(rows)}', end='', file=sys.stderr)
print(file=sys.stderr)

Set the key, the database URL and your plan's requests per second, then run a batch. Use BATCH_SIZE to change the 1,000 rows:

Terminal
read -rs OPENGEOCODING_API_KEY && export OPENGEOCODING_API_KEY
export DATABASE_URL=postgres://app@db.example.com/crm
export REQUESTS_PER_SECOND=2
bash geocode_table.sh

Each successful search spends one credit, including one that finds nothing. Those rows are marked done with empty coordinates, so they are not paid for twice. If the run stops early, for example when the credits run out, the rows that finished are still saved and the script exits with an error. Errors returned by the API do not consume credits.

3. Review the matches

good_match is true for a confident full match. False means a partial match, such as the street without the requested house number. Check those before you use the point for delivery, pricing or a site visit:

psql
SELECT good_match, count(*) FROM customers
WHERE geocoded_at IS NOT NULL
GROUP BY good_match;

-- Rows to review by hand
SELECT id, address, matched_address FROM customers
WHERE geocoded_at IS NOT NULL AND good_match IS NOT TRUE
ORDER BY id LIMIT 50;

Coverage and address detail vary by country and source. You can keep the results in your database with no deletion deadline, subject to the underlying data licences.

4. Keep new and edited rows geocoded

Run the script on a schedule. Each run takes the next batch of rows without a result: new rows, edited addresses and anything a previous run did not finish. At the Free plan's 2 requests per second, 1,000 rows take about 9 minutes, so leave time between runs and let only one run at a time:

crontab
*/10 * * * * cd /opt/geocode && flock -n /tmp/geocode_table.lock bash geocode_table.sh

For a first import of more rows than your monthly allowance, see the plans or the Enterprise option for millions of rows.

5. Query the points with PostGIS

With the PostGIS extension, a generated column turns lat and lon into a point that stays in sync with them, and a GiST index makes distance queries fast:

psql
CREATE EXTENSION IF NOT EXISTS postgis;

ALTER TABLE customers ADD COLUMN location geography(Point, 4326)
  GENERATED ALWAYS AS (ST_SetSRID(ST_MakePoint(lon, lat), 4326)::geography) STORED;
CREATE INDEX customers_location ON customers USING gist (location);

-- Customers within 1 km of a point (longitude first)
SELECT id, address FROM customers
WHERE ST_DWithin(location, ST_MakePoint(2.36, 48.855)::geography, 1000);

Why not call the API from inside PostgreSQL?

Extensions can make HTTP requests from SQL, but then every lookup runs inside a transaction and holds its locks while it waits on the network, the API key lives in the database, and most managed PostgreSQL services do not offer the extension. Geocoding in batches outside the database keeps writes short and works on any PostgreSQL. To geocode a single address as a user enters it, call the API from your application instead, as in the Python or Node.js guide. For coordinates you already have, use reverse geocoding.