Add place-name autocomplete
Use the published finite-state transducerFST (finite-state transducer). A compact automaton that reads an input sequence and emits an output sequence. Mailwoman encodes gazetteer names and street affixes as FSTs for fast prefix matching and prior injection without search overhead. (FSTFST (finite-state transducer). A compact automaton that reads an input sequence and emits an output sequence. Mailwoman encodes gazetteer names and street affixes as FSTs for fast prefix matching and prior injection without search overhead.) to suggest place namestoponymA proper name for a geographic place. as someone types. The FSTFST (finite-state transducer). A compact automaton that reads an input sequence and emits an output sequence. Mailwoman encodes gazetteer names and street affixes as FSTs for fast prefix matching and prior injection without search overhead. in @mailwoman/neural-weights-en-us@11.0.0 runs without a geographic database. Each suggestion is a place nametoponymA proper name for a geographic place. with its Who's On FirstWOF (Who's On First). An open-source gazetteer of places maintained by Mapzen/whosonfirst. Mailwoman builds a custom SQLite database from WOF GeoJSON repos, extended with postcode data, importance scores, and coincident-role relations. ID. Coordinates, streetstreetThe named linear feature along which house numbers are ordered. Decomposes into a name plus street affixes; one of the Tier 2 fine labels. addresses and delivery evidence come from other sources. This example serves a small JSON endpoint and sends a fixed sequence of input events through it.
Prerequisites
^24.22.3 || >=26.13.1"type": "module" in its package.jsonInstall the two packages the example uses:
- npm
- Yarn
- pnpm
- Bun
npm install @mailwoman/resolver-wof-sqlite @mailwoman/neural-weights-en-us
yarn add @mailwoman/resolver-wof-sqlite @mailwoman/neural-weights-en-us
pnpm add @mailwoman/resolver-wof-sqlite @mailwoman/neural-weights-en-us
bun add @mailwoman/resolver-wof-sqlite @mailwoman/neural-weights-en-us
Check that node_modules/@mailwoman/neural-weights-en-us/fst-en-us.bin exists in this project before starting the server. The path is relative to the project directory. The data and locales reference distinguishes this place-name index from the geographic databases needed to resolve coordinates.
Serve suggestions and check the request count
Save this code as autocomplete.ts. It loads the FSTFST (finite-state transducer). A compact automaton that reads an input sequence and emits an output sequence. Mailwoman encodes gazetteer names and street affixes as FSTs for fast prefix matching and prior injection without search overhead. once, exposes GET /suggest?q=..., and runs a local client against seven input events. The client skips inputs shorter than three trimmed characters and suppresses an event when trimming leaves the same query as the previous request. The application chooses these rules.
import { createServer } from "node:http"
import { readFile } from "node:fs/promises"
import { autocomplete, deserializeFST } from "@mailwoman/resolver-wof-sqlite/fst"
interface Suggestion {
name: string
placetype: string
wofID: number
}
const fst = deserializeFST(await readFile("node_modules/@mailwoman/neural-weights-en-us/fst-en-us.bin"))
let requests = 0
const server = createServer((request, response) => {
const url = new URL(request.url ?? "/", "http://localhost")
if (url.pathname !== "/suggest") {
response.writeHead(404).end()
return
}
requests++
const query = url.searchParams.get("q")?.trim() ?? ""
const entries: Suggestion[] =
query.length < 3
? []
: autocomplete(fst, query, { maxSuggestions: 2, dedupeByName: true }).suggestions.map(
({ name, placetype, wofID }) => ({ name, placetype, wofID })
)
response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ entries }))
})
await new Promise<void>((resolve) => {
server.listen(0, "127.0.0.1", resolve)
})
const address = server.address()
if (typeof address === "string" || address === null) throw new Error("Expected TCP address")
let lastQuery = ""
for (const input of ["s", "sa", "san", "san ", "san f", "san fr", "san franc"]) {
const query = input.trim()
if (query.length < 3) {
console.log(`${JSON.stringify(input)}: skipped (short)`)
continue
}
if (query === lastQuery) {
console.log(`${JSON.stringify(input)}: skipped (unchanged)`)
continue
}
lastQuery = query
const response = await fetch(`http://127.0.0.1:${address.port}/suggest?q=${encodeURIComponent(query)}`)
if (!response.ok) throw new Error(`HTTP ${response.status}`)
const data = (await response.json()) as { entries: Suggestion[] }
console.log(
`${JSON.stringify(input)}: ${data.entries.map(({ name, placetype }) => `${name} (${placetype})`).join("; ")}`
)
}
console.log(`HTTP requests: ${requests} of 7 input events`)
server.close()
Run node autocomplete.ts. The published 11.0.0 packages returned this complete output in the local check:
"s": skipped (short)
"sa": skipped (short)
"san": San Antonio (locality); San Diego (locality)
"san ": skipped (unchanged)
"san f": San Francisco (locality); San Fernando (locality)
"san fr": San Francisco (locality); San Francisco Township (localadmin)
"san franc": San Francisco (locality); San Francisco Township (localadmin)
HTTP requests: 4 of 7 input events
Four of the seven input events made HTTP requests: san, san f, san fr, and san franc. The first two events were below this example's three-character rule, and san trimmed to the already-requested san. The server also checks short queries, so a direct request gets the same length rule as the client. dedupeByName: true keeps one entry per displayed name. It changes the second result for san franc from the CLI's default. The CLI example on the capabilities page leaves deduplicationrecord matchingThe process of determining whether two database records refer to the same real-world entity. Mailwoman's matcher uses a geocode-first approach (match the resolved place, not the address string) with Fellegi-Sunter probabilistic scoring. off.
In an application, send the search field's current value to /suggest using the same trim, length, and unchanged-query checks. Render the returned entries as selectable place-name suggestions and keep each wofID as its place identifier. The example measures the request count for one fixed typing sequence. Measure response latency on your host and with your input mix before choosing a debounce delay.
The FSTFST (finite-state transducer). A compact automaton that reads an input sequence and emits an output sequence. Mailwoman encodes gazetteer names and street affixes as FSTs for fast prefix matching and prior injection without search overhead. returns ranked gazetteergazetteerA geographical index that maps place names and postcodes to real-world coordinates. Mailwoman uses a custom-built Who's On First (WOF) SQLite database as its gazetteer — the 'atlas' half of the grammar/atlas architecture. names and a wofID for each suggestion. See geocoding for the separate lookup that supplies a coordinate, and confidence and limits for evidence boundaries.