Skip to main content

Batch geocode a file of records

Use this procedure to geocode a file of records that each have an ID. The script on this page runs one geocoder process for the whole file. It writes one output record per input row, marks the rows left without a coordinate, and skips rows already finished when you run it again.

Geocode a file of addresses introduces the result fields this guide reads.

Prerequisites​

  • Node.js ^24.22.3 || >=26.13.1
  • ECMAScript module project with "type": "module" in its package.json
  • Start by installing the required packages:

    sh
    npm install mailwoman

    Install the data for the places your records cover. The example rows need the global place candidates, French address pointssitus dataA dataset of exact address-point coordinates (rooftop-level). Mailwoman's geocoder uses a national situs layer (124.9M US points built from state address-point sources) as the highest-precision tier of the geocode cascade., and the Washington, DC and Vermont address pointssitus dataA dataset of exact address-point coordinates (rooftop-level). Mailwoman's geocoder uses a national situs layer (124.9M US points built from state address-point sources) as the highest-precision tier of the geocode cascade.:

    sh
    export MAILWOMAN_DATA_ROOT="$HOME/mailwoman-data"

    npx mailwoman data pull candidate fr
    npx mailwoman data pull us --only us-dc
    npx mailwoman data pull us --only us-vt

    Data and locales lists every bundleevidence bundleThe pair of retrieval-augmented input channels (street-type + locality-surface) that feed lexicon membership as soft per-token evidence alongside the text. Shipped in 6.7.0; trained natively from step 0 in the from-scratch base line.. The output below was captured with local builds of these bundlesevidence bundleThe pair of retrieval-augmented input channels (street-type + locality-surface) that feed lexicon membership as soft per-token evidence alongside the text. Shipped in 6.7.0; trained natively from step 0 in the from-scratch base line. that are newer than the 11.0.0 registry entries.

    1. Prepare the input​

    Save the records as addresses.csv, with a header row, an ID, and the address after the first comma:

    text
    id,address
    a1,1600 Pennsylvania Ave NW, Washington, DC 20500
    a2,1 Main St, Burlington, VT 05401
    a3,
    a4,Springfield, IL
    a5,12 Rue de Rivoli, 75001 Paris, France
    a6,Main Street

    Row a3 has no address. The script reads everything after the first comma as the address, so addresses may contain commas. It reads one record per line, so convert a file with quoted CSV fields or line breaks inside a field to that shape first.

    2. Save the batch script​

    mailwoman geocode --stdin reads one address per line and writes one JSON result per non-empty line, in input order. An empty or whitespace-only line gets no result line. The script below therefore records empty addresses itself and sends only non-empty ones to the geocoder. It also checks each result's input field against the address it sent, so each result stays paired with its own ID.

    Save this file as batch-geocode.ts:

    ts
    import { spawn } from "node:child_process"
    import { appendFileSync, existsSync, readFileSync } from "node:fs"
    import { createInterface } from "node:readline"

    interface InputRow {
    id: string
    address: string
    }

    interface GeocodeResult {
    input: string
    lat: number | null
    lon: number | null
    resolution_tier: string
    coordinate_source: { source: string } | null
    }

    type OutputRecord =
    | { id: string; status: "failed"; reason: string }
    | {
    id: string
    status: "resolved" | "unresolved"
    tier: string
    lat: number | null
    lon: number | null
    source: string | null
    }

    const inputPath = process.argv[2] ?? "addresses.csv"
    const outputPath = process.argv[3] ?? "geocoded.jsonl"

    // Each input line is `id,address`. The address is everything after the first comma.
    const rows: InputRow[] = readFileSync(inputPath, "utf8")
    .split("\n")
    .slice(1)
    .filter((line) => line.includes(","))
    .map((line) => {
    const comma = line.indexOf(",")

    return {
    id: line.slice(0, comma),
    address: line
    .slice(comma + 1)
    .replaceAll(/\s+/g, " ")
    .trim(),
    }
    })

    const done = new Set<string>(
    existsSync(outputPath)
    ? readFileSync(outputPath, "utf8")
    .split("\n")
    .filter(Boolean)
    .map((line) => (JSON.parse(line) as OutputRecord).id)
    : []
    )

    const pending = rows.filter((row) => !done.has(row.id))
    const write = (record: OutputRecord) => appendFileSync(outputPath, `${JSON.stringify(record)}\n`)

    for (const row of pending.filter((candidate) => candidate.address === "")) {
    write({ id: row.id, status: "failed", reason: "empty address" })
    }

    const work = pending.filter((row) => row.address !== "")

    if (!work.length) {
    console.log(`nothing to geocode; ${done.size} rows were already done`)

    process.exit(0)
    }

    const started = Date.now()

    const geocoder = spawn("npx", ["mailwoman", "geocode", "--stdin"], {
    stdio: ["pipe", "pipe", "ignore"],
    })

    let next = 0

    createInterface({ input: geocoder.stdout }).on("line", (line) => {
    const row = work[next++]
    const result = JSON.parse(line) as GeocodeResult

    if (result.input !== row.address) {
    throw new Error(`result for "${result.input}" belongs to a row other than ${row.id}`)
    }

    write({
    id: row.id,
    status: result.lat == null ? "unresolved" : "resolved",
    tier: result.resolution_tier,
    lat: result.lat,
    lon: result.lon,
    source: result.coordinate_source?.source ?? null,
    })
    })

    for (const row of work) {
    geocoder.stdin.write(`${row.address}\n`)
    }

    geocoder.stdin.end()

    geocoder.on("close", (code) => {
    const seconds = ((Date.now() - started) / 1000).toFixed(1)

    console.log(
    `geocoder exit ${code}: ${next} of ${work.length} rows written in ${seconds} s; ${done.size} rows were already done`
    )

    if (code !== 0 || next !== work.length) {
    process.exitCode = 1
    }
    })

    The script appends each record to the output as soon as its result arrives. Each output record keeps id, status, tier, lat, lon and source, or reason for a failed row. Add fields from the result schema as you need them.

    3. Run the batch​

    sh
    node batch-geocode.ts
    text
    geocoder exit 0: 5 of 5 rows written in 7.7 s; 0 rows were already done

    The elapsed time depends on the host. The script exits 0 when the geocoder exited 0 and every sent row received a result. Otherwise it exits 1.

    4. Read the output​

    geocoded.jsonl holds one record for each of the six input rows:

    json
    {"id":"a3","status":"failed","reason":"empty address"}
    {"id":"a1","status":"resolved","tier":"address_point","lat":38.89767510742324,"lon":-77.03654697024702,"source":"overture:NAD"}
    {"id":"a2","status":"resolved","tier":"address_point","lat":44.4757187630707,"lon":-73.21948742524441,"source":"overture:NAD"}
    {"id":"a4","status":"resolved","tier":"admin","lat":39.797328,"lon":-89.645547,"source":null}
    {"id":"a5","status":"resolved","tier":"address_point","lat":48.855602,"lon":2.35995,"source":"ban:fr"}
    {"id":"a6","status":"unresolved","tier":"admin","lat":null,"lon":null,"source":null}

    The script writes the empty-address records first and the geocoded records after them in input order, and a resumed run appends to the file, so join records to your input by id rather than by position. Each record has one of three statuses:

    • failed means the row had no address to send.
    • unresolved means the geocoder returned no coordinate. Send these rows to review.
    • resolved means the geocoder returned a coordinate. Check tier before using it: a4, Springfield, IL, resolved to a citylocalityThe city / town / settlement component of an address: a populated place sitting between region and neighborhood in the hierarchy.-level point at the admin tier, while the other resolved rows are single address pointssitus dataA dataset of exact address-point coordinates (rooftop-level). Mailwoman's geocoder uses a national situs layer (124.9M US points built from state address-point sources) as the highest-precision tier of the geocode cascade..

    5. Resume a stopped run​

    Run the same command again. The script reads the IDs already in geocoded.jsonl and sends only the rest:

    sh
    node batch-geocode.ts
    text
    nothing to geocode; 6 rows were already done

    If a run stops partway, the rows written before it stopped keep their records, and the next run geocodes the remaining rows. To geocode everything again, delete or rename the output file first.

    Resource use​

    The script runs one geocoder process for the whole file. One run on the host used for this page geocoded a 300-row file in 7.5 seconds of wall-clock time, including modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' and data loading. It used 186% of one CPU core on average, and its peak resident memory was 601,540 kB. Those 300 rows repeated six addresses, so varied data can run at a different rate. Measure your own file on your own hardware before planning a large batchbatch sizeHow many examples the model processes before each parameter update. Larger batches give smoother gradients but cost more memory; gradient accumulation simulates a big batch on a small GPU..

    To use more cores, split the input into separate files and run one script per file, each with its own output file. Each process loads its own copy of the modelneural classifierThe machine learning model at the core of Mailwoman's parser — a transformer encoder (~30M parameters) trained from scratch to do BIO token classification over addresses. It learns the 'grammar' of address formats; the gazetteer supplies the 'atlas.' and data, so memory use grows with the number of processes.

    For batchesbatch sizeHow many examples the model processes before each parameter update. Larger batches give smoother gradients but cost more memory; gradient accumulation simulates a big batch on a small GPU. sent over HTTP, the native server's POST /v1/batch route accepts an addresses array and returns 413 when the request is too large. The HTTP reference describes it, and Run the Mailwoman HTTP server shows how to start the server.