@mailwoman/resolver-wof-sqlite 11.1.0 → 11.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/lib/ancestry/backfill.ts +13 -43
- package/lib/build/candidate.ts +42 -2
- package/lib/candidate/alias-bags.ts +54 -14
- package/lib/candidate/importance.ts +4 -3
- package/lib/candidate/key-fold.ts +132 -0
- package/lib/candidate/lookup.ts +23 -13
- package/lib/candidate/nickname-namesakes.ts +140 -0
- package/lib/fst/binary-matcher.ts +26 -41
- package/lib/fst/format.ts +144 -7
- package/lib/fst/serialize.ts +92 -63
- package/lib/geonames/aliases.ts +8 -15
- package/lib/importance-source.ts +210 -0
- package/lib/primary-preference.ts +40 -2
- package/lib/street/normalize.ts +42 -0
- package/out/ancestry/backfill.d.ts +14 -9
- package/out/ancestry/backfill.d.ts.map +1 -1
- package/out/ancestry/backfill.js +4 -42
- package/out/ancestry/backfill.js.map +1 -1
- package/out/build/candidate.d.ts +20 -0
- package/out/build/candidate.d.ts.map +1 -1
- package/out/build/candidate.js +14 -2
- package/out/build/candidate.js.map +1 -1
- package/out/candidate/alias-bags.d.ts +8 -0
- package/out/candidate/alias-bags.d.ts.map +1 -1
- package/out/candidate/alias-bags.js +43 -12
- package/out/candidate/alias-bags.js.map +1 -1
- package/out/candidate/importance.d.ts.map +1 -1
- package/out/candidate/importance.js +4 -3
- package/out/candidate/importance.js.map +1 -1
- package/out/candidate/key-fold.d.ts +55 -0
- package/out/candidate/key-fold.d.ts.map +1 -0
- package/out/candidate/key-fold.js +80 -0
- package/out/candidate/key-fold.js.map +1 -0
- package/out/candidate/lookup.d.ts.map +1 -1
- package/out/candidate/lookup.js +22 -12
- package/out/candidate/lookup.js.map +1 -1
- package/out/candidate/nickname-namesakes.d.ts +32 -0
- package/out/candidate/nickname-namesakes.d.ts.map +1 -0
- package/out/candidate/nickname-namesakes.js +98 -0
- package/out/candidate/nickname-namesakes.js.map +1 -0
- package/out/fst/binary-matcher.d.ts.map +1 -1
- package/out/fst/binary-matcher.js +9 -30
- package/out/fst/binary-matcher.js.map +1 -1
- package/out/fst/format.d.ts +60 -9
- package/out/fst/format.d.ts.map +1 -1
- package/out/fst/format.js +97 -6
- package/out/fst/format.js.map +1 -1
- package/out/fst/serialize.d.ts.map +1 -1
- package/out/fst/serialize.js +66 -54
- package/out/fst/serialize.js.map +1 -1
- package/out/geonames/aliases.d.ts.map +1 -1
- package/out/geonames/aliases.js +7 -11
- package/out/geonames/aliases.js.map +1 -1
- package/out/importance-source.d.ts +90 -0
- package/out/importance-source.d.ts.map +1 -0
- package/out/importance-source.js +133 -0
- package/out/importance-source.js.map +1 -0
- package/out/primary-preference.d.ts +20 -1
- package/out/primary-preference.d.ts.map +1 -1
- package/out/primary-preference.js +31 -1
- package/out/primary-preference.js.map +1 -1
- package/out/street/normalize.d.ts +19 -0
- package/out/street/normalize.d.ts.map +1 -1
- package/out/street/normalize.js +38 -0
- package/out/street/normalize.js.map +1 -1
- package/package.json +12 -12
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Phase 4.2 of the mailwoman neural-resolver plan — see [`docs/plan/phases/PHASE
|
|
|
6
6
|
|
|
7
7
|
## Installation
|
|
8
8
|
|
|
9
|
-
```
|
|
9
|
+
```sh npm2yarn
|
|
10
10
|
npm install @mailwoman/resolver-wof-sqlite
|
|
11
11
|
```
|
|
12
12
|
|
|
@@ -90,7 +90,7 @@ The Geocode Earth team mirrors WOF SQLite distributions at <https://data.geocode
|
|
|
90
90
|
| `whosonfirst-data-admin-us-latest.db.bz2` | ~845 MB | US administrative places (country / region / locality / borough). |
|
|
91
91
|
| `whosonfirst-data-postalcode-us-latest.db.bz2` | ~320 MB | US postcodes. |
|
|
92
92
|
|
|
93
|
-
```
|
|
93
|
+
```sh
|
|
94
94
|
curl -L -o whosonfirst-data-admin-us-latest.db.bz2 \
|
|
95
95
|
https://data.geocode.earth/wof/dist/sqlite/whosonfirst-data-admin-us-latest.db.bz2
|
|
96
96
|
bunzip2 whosonfirst-data-admin-us-latest.db.bz2
|
|
@@ -107,7 +107,7 @@ Upstream WOF SQLite distributions ship a `places` table but **not** an FTS5 inde
|
|
|
107
107
|
|
|
108
108
|
A one-shot operator script ships with this package as a `bin`:
|
|
109
109
|
|
|
110
|
-
```
|
|
110
|
+
```sh
|
|
111
111
|
mailwoman gazetteer build fts /path/to/whosonfirst-data-admin-us-latest.db
|
|
112
112
|
```
|
|
113
113
|
|
|
@@ -122,7 +122,7 @@ The CLI:
|
|
|
122
122
|
`populating-bbox` and `done`.
|
|
123
123
|
- Exits 0 with a no-op message if both indexes already exist.
|
|
124
124
|
|
|
125
|
-
```
|
|
125
|
+
```sh
|
|
126
126
|
# Refresh after pulling a newer WOF dump
|
|
127
127
|
mailwoman gazetteer build fts /path/to/wof.db --drop
|
|
128
128
|
```
|
|
@@ -133,7 +133,7 @@ mailwoman gazetteer build fts /path/to/wof.db --drop
|
|
|
133
133
|
|
|
134
134
|
Builds a trimmed WOF SQLite distribution sized for browser-side deployments (Path B of the demo plan). The full admin-US distribution is ~4 GB. A slim US bundle with the top-1k localities by population plus all postcodes lands at **~35 MB**, small enough to ship as a static asset.
|
|
135
135
|
|
|
136
|
-
```
|
|
136
|
+
```sh
|
|
137
137
|
# Defaults: --top 1000 localities, --countries US, drops geojson after building aux tables
|
|
138
138
|
# The slim wof-hot.db distribution is RETIRED (2026-06-20): the demo byte-range-resolves
|
|
139
139
|
# against the global candidate table. `buildSlimWOFDatabase` remains importable from
|
package/lib/ancestry/backfill.ts
CHANGED
|
@@ -7,71 +7,41 @@
|
|
|
7
7
|
* Must run after `populateAncestors` and before the build freezes.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import {
|
|
10
|
+
import type { WOFFeature } from "@mailwoman/gazetteer/whosonfirst"
|
|
11
11
|
import { hierarchyAncestorsInAnyBranch } from "@mailwoman/gazetteer/whosonfirst/hierarchy"
|
|
12
12
|
import type { DatabaseClient } from "@mailwoman/sqlite/client"
|
|
13
|
-
import { PathBuilder, type PathBuilderLike } from "path-ts"
|
|
14
|
-
import { Globerator } from "spliterator/node/fs"
|
|
15
13
|
|
|
16
14
|
import type { WOFDatabase } from "#schema"
|
|
17
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Reads the WOF record with an id, such as a primary-key read of the WOF record store, or returns `null`.
|
|
18
|
+
*/
|
|
19
|
+
export type WOFFeatureReader = (
|
|
20
|
+
id: number
|
|
21
|
+
) => Pick<WOFFeature, "properties"> | null | Promise<Pick<WOFFeature, "properties"> | null>
|
|
22
|
+
|
|
18
23
|
const TOP_PLACETYPES = new Set(["country", "continent", "empire", "ocean", "marinearea", "planet"])
|
|
19
24
|
|
|
20
25
|
export interface AncestryBackfillResult {
|
|
21
26
|
placesFixed: number
|
|
22
27
|
rowsAdded: number
|
|
23
28
|
/**
|
|
24
|
-
* Candidates
|
|
29
|
+
* Candidates the reader returned no record for (non-WOF backfilled places or absent repos),
|
|
25
30
|
* skipped rather than treated as an error.
|
|
26
31
|
*/
|
|
27
32
|
noGeojson: number
|
|
28
33
|
}
|
|
29
34
|
|
|
30
|
-
/**
|
|
31
|
-
* Discover the `data` directories under a WOF repos root that hold attached geojson,
|
|
32
|
-
* accepting both the nested lab layout and a flat layout at most two directory levels deep.
|
|
33
|
-
*/
|
|
34
|
-
export async function discoverAdminDataRoots(reposRoot: PathBuilderLike): Promise<PathBuilder[]> {
|
|
35
|
-
const roots: PathBuilder[] = []
|
|
36
|
-
|
|
37
|
-
const visit = async (dir: PathBuilder, depth: number): Promise<void> => {
|
|
38
|
-
if (depth > 2) return
|
|
39
|
-
|
|
40
|
-
let names: string[]
|
|
41
|
-
|
|
42
|
-
try {
|
|
43
|
-
names = (await Globerator.from("*", { cwd: dir, withFileTypes: true, onlyFiles: false }).toArray())
|
|
44
|
-
.filter((entry) => entry.isDirectory())
|
|
45
|
-
.map((entry) => entry.name)
|
|
46
|
-
} catch {
|
|
47
|
-
return
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
for (const name of names) {
|
|
51
|
-
const child = dir(name)
|
|
52
|
-
|
|
53
|
-
if (name === "data") {
|
|
54
|
-
roots.push(child)
|
|
55
|
-
} else if (name.startsWith("whosonfirst-data")) {
|
|
56
|
-
await visit(child, depth + 1)
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
await visit(PathBuilder.from(reposRoot), 0)
|
|
62
|
-
|
|
63
|
-
return roots
|
|
64
|
-
}
|
|
65
|
-
|
|
66
35
|
/**
|
|
67
36
|
* Insert missing ancestor rows for places whose ancestry chain ended before reaching a country.
|
|
68
37
|
*
|
|
69
|
-
* The function reads `wof:hierarchy`
|
|
38
|
+
* The function reads each candidate's `wof:hierarchy` through `readFeature`
|
|
39
|
+
* and runs in one transaction under the caller's connection.
|
|
70
40
|
* `opts.maxID` bounds the scan to avoid probing synthetic-id Overture and GeoNames rows.
|
|
71
41
|
*/
|
|
72
42
|
export async function backfillAncestorsFromHierarchy(
|
|
73
43
|
db: DatabaseClient<WOFDatabase>,
|
|
74
|
-
|
|
44
|
+
readFeature: WOFFeatureReader,
|
|
75
45
|
opts: { maxID?: number } = {}
|
|
76
46
|
): Promise<AncestryBackfillResult> {
|
|
77
47
|
const maxID = opts.maxID ?? Number.MAX_SAFE_INTEGER
|
|
@@ -124,7 +94,7 @@ export async function backfillAncestorsFromHierarchy(
|
|
|
124
94
|
|
|
125
95
|
for (const { id, placetype } of candidates) {
|
|
126
96
|
if (placetype && TOP_PLACETYPES.has(placetype)) continue
|
|
127
|
-
const gj = await
|
|
97
|
+
const gj = await readFeature(id)
|
|
128
98
|
const hierarchy = gj?.properties?.["wof:hierarchy"]
|
|
129
99
|
|
|
130
100
|
if (!hierarchy || !hierarchy.length) {
|
package/lib/build/candidate.ts
CHANGED
|
@@ -17,7 +17,9 @@ import { stageCountryDisplayNames } from "#candidate/country-display-names"
|
|
|
17
17
|
import { foldExtract } from "#candidate/extract-fold"
|
|
18
18
|
import { createCandidateFTS } from "#candidate/fts"
|
|
19
19
|
import { IMPORTANCE_JOIN_RADIUS_KM, loadImportanceIndex } from "#candidate/importance"
|
|
20
|
+
import { applyCandidateKeyFold, type CandidateKeyFold } from "#candidate/key-fold"
|
|
20
21
|
import { GLOSS_KEY_THRESHOLD, stampNameRoles } from "#candidate/name-roles"
|
|
22
|
+
import { refuseNicknamesOfNamesakes } from "#candidate/nickname-namesakes"
|
|
21
23
|
import type { PlaceAttrs } from "#candidate/place-attrs"
|
|
22
24
|
import {
|
|
23
25
|
CANDIDATE_COLUMNS,
|
|
@@ -96,6 +98,14 @@ export interface BuildCandidateOptions {
|
|
|
96
98
|
* @defaultValue {@linkcode GLOSS_KEY_THRESHOLD}
|
|
97
99
|
*/
|
|
98
100
|
glossKeyThreshold?: number
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Folds applied to every `name_key` after `normalizeLocalityForKey`, recorded in
|
|
104
|
+
* the artifact so its reader folds query keys the same way.
|
|
105
|
+
*
|
|
106
|
+
* @defaultValue none
|
|
107
|
+
*/
|
|
108
|
+
keyFolds?: readonly CandidateKeyFold[]
|
|
99
109
|
}
|
|
100
110
|
|
|
101
111
|
/**
|
|
@@ -106,6 +116,11 @@ export interface BuildCandidateResult {
|
|
|
106
116
|
places: number
|
|
107
117
|
primaries: number
|
|
108
118
|
aliases: number
|
|
119
|
+
/**
|
|
120
|
+
* The count of alias rows staged as a name's key with its apostrophe-like marks
|
|
121
|
+
* removed (`hawaii` for `Hawaiʻi`), which `aliases` excludes.
|
|
122
|
+
*/
|
|
123
|
+
markFreeAliases: number
|
|
109
124
|
|
|
110
125
|
/**
|
|
111
126
|
* The count of region aliases dropped because another region in the same
|
|
@@ -114,6 +129,14 @@ export interface BuildCandidateResult {
|
|
|
114
129
|
* The count is always zero for a source without a `names` table.
|
|
115
130
|
*/
|
|
116
131
|
regionOfficialRefused: number
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The count of alias rows from a colloquial or unclassified name dropped
|
|
135
|
+
* because a populated place holds the same key by a real name.
|
|
136
|
+
*
|
|
137
|
+
* The count is always zero for a source without a `names` table.
|
|
138
|
+
*/
|
|
139
|
+
nicknameRefused: number
|
|
117
140
|
abbrevs: number
|
|
118
141
|
postcodes: number
|
|
119
142
|
|
|
@@ -401,7 +424,7 @@ export async function buildCandidateTable(opts: BuildCandidateOptions): Promise<
|
|
|
401
424
|
|
|
402
425
|
const iso2ByCountryID = new Map([...ccodes].map(([code, id]) => [id, code]))
|
|
403
426
|
|
|
404
|
-
const { nAlias, nBare, keyCounts, regionOfficialRefused } = explodeAliasBags(src, kdb, attrs, stageRow, {
|
|
427
|
+
const { nAlias, nBare, nMarkFree, keyCounts, regionOfficialRefused } = explodeAliasBags(src, kdb, attrs, stageRow, {
|
|
405
428
|
regionPlacetypeID: ptID("region"),
|
|
406
429
|
ccID,
|
|
407
430
|
bareName: (countryID, alias) => bareAdminName(iso2ByCountryID.get(countryID) ?? "", alias),
|
|
@@ -409,7 +432,8 @@ export async function buildCandidateTable(opts: BuildCandidateOptions): Promise<
|
|
|
409
432
|
|
|
410
433
|
progress(
|
|
411
434
|
"aliases",
|
|
412
|
-
`${nAlias.toLocaleString()} aliases; ${nBare.toLocaleString()} bare admin aliases` +
|
|
435
|
+
`${nAlias.toLocaleString()} aliases; ${nBare.toLocaleString()} bare admin aliases; ` +
|
|
436
|
+
`${nMarkFree.toLocaleString()} mark-free aliases` +
|
|
413
437
|
(regionOfficialRefused
|
|
414
438
|
? `; ${regionOfficialRefused.toLocaleString()} region aliases refused as another region's official name`
|
|
415
439
|
: "")
|
|
@@ -433,6 +457,14 @@ export async function buildCandidateTable(opts: BuildCandidateOptions): Promise<
|
|
|
433
457
|
kdb.exec("COMMIT")
|
|
434
458
|
progress("abbrevs", `${nAbbr.toLocaleString()} abbrevs`)
|
|
435
459
|
|
|
460
|
+
const nicknames = refuseNicknamesOfNamesakes(src, kdb, attrs)
|
|
461
|
+
|
|
462
|
+
progress(
|
|
463
|
+
"nicknames",
|
|
464
|
+
`${nicknames.rows.toLocaleString()} colloquial or unclassified alias rows refused on ` +
|
|
465
|
+
`${nicknames.keys.toLocaleString()} keys a populated place holds by a real name`
|
|
466
|
+
)
|
|
467
|
+
|
|
436
468
|
const roles = stampNameRoles({
|
|
437
469
|
src,
|
|
438
470
|
out: kdb,
|
|
@@ -541,6 +573,12 @@ export async function buildCandidateTable(opts: BuildCandidateOptions): Promise<
|
|
|
541
573
|
kdb.exec(`INSERT OR IGNORE INTO candidate (${cols}) SELECT ${cols} FROM cand_stage ORDER BY ${keyOrder};`)
|
|
542
574
|
await kdb.schema.dropTable("cand_stage").execute()
|
|
543
575
|
|
|
576
|
+
for (const fold of opts.keyFolds ?? []) {
|
|
577
|
+
const { rekeyed, merged } = await applyCandidateKeyFold(kdb, fold)
|
|
578
|
+
|
|
579
|
+
progress("key-fold", `${fold}: ${rekeyed.toLocaleString()} rows rekeyed, ${merged.toLocaleString()} merged`)
|
|
580
|
+
}
|
|
581
|
+
|
|
544
582
|
progress("fts", "building FTS5-trigram fuzzy index")
|
|
545
583
|
createCandidateFTS(kdb)
|
|
546
584
|
|
|
@@ -557,7 +595,9 @@ export async function buildCandidateTable(opts: BuildCandidateOptions): Promise<
|
|
|
557
595
|
places: attrs.size,
|
|
558
596
|
primaries: nPrim,
|
|
559
597
|
aliases: nAlias,
|
|
598
|
+
markFreeAliases: nMarkFree,
|
|
560
599
|
regionOfficialRefused,
|
|
600
|
+
nicknameRefused: nicknames.rows,
|
|
561
601
|
abbrevs: nAbbr,
|
|
562
602
|
postcodes: nPostcode,
|
|
563
603
|
postcodeAliases: nPostcodeAlias,
|
|
@@ -12,7 +12,7 @@ import type { PlaceAttrs, StageRow } from "#candidate/place-attrs"
|
|
|
12
12
|
import type { CandidateDatabase } from "#candidate/schema"
|
|
13
13
|
import { ALIAS_SEPARATOR } from "#fts"
|
|
14
14
|
import type { WOFDatabase } from "#schema"
|
|
15
|
-
import { normalizeLocalityForKey } from "#street/normalize"
|
|
15
|
+
import { type NameKey, normalizeLocalityForKey, withoutApostropheLikeMarks } from "#street/normalize"
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* The official name of every current region, keyed `${country id}\0${name key}` →
|
|
@@ -55,6 +55,13 @@ function officialNameHoldersByRegion(
|
|
|
55
55
|
* With `regionPlacetypeID` and `ccID` given, a region's alias that's another same-country region's
|
|
56
56
|
* official name is refused and counted rather than staged (see {@link officialNameHoldersByRegion}).
|
|
57
57
|
* Without them the pass stages every alias.
|
|
58
|
+
*
|
|
59
|
+
* Each key holding an apostrophe-like mark, the primary's included, also stages
|
|
60
|
+
* its mark-free form ({@link withoutApostropheLikeMarks}).
|
|
61
|
+
* The count excludes those forms.
|
|
62
|
+
*
|
|
63
|
+
* The gloss detector compares the count with its threshold, and a mark-free form
|
|
64
|
+
* spells a name the count already includes.
|
|
58
65
|
*/
|
|
59
66
|
export function explodeAliasBags(
|
|
60
67
|
src: DatabaseClient<WOFDatabase>,
|
|
@@ -72,9 +79,16 @@ export function explodeAliasBags(
|
|
|
72
79
|
*/
|
|
73
80
|
bareName?: (countryID: number, alias: string) => string | null
|
|
74
81
|
} = {}
|
|
75
|
-
): {
|
|
82
|
+
): {
|
|
83
|
+
nAlias: number
|
|
84
|
+
nBare: number
|
|
85
|
+
nMarkFree: number
|
|
86
|
+
keyCounts: Map<number, number>
|
|
87
|
+
regionOfficialRefused: number
|
|
88
|
+
} {
|
|
76
89
|
let nAlias = 0
|
|
77
90
|
let nBare = 0
|
|
91
|
+
let nMarkFree = 0
|
|
78
92
|
let regionOfficialRefused = 0
|
|
79
93
|
const keyCounts = new Map<number, number>()
|
|
80
94
|
|
|
@@ -90,14 +104,35 @@ export function explodeAliasBags(
|
|
|
90
104
|
const a = attrs.get(id)
|
|
91
105
|
const alt = r.alt_names as string | null
|
|
92
106
|
|
|
93
|
-
if (!a
|
|
107
|
+
if (!a) continue
|
|
94
108
|
const seen = new Set<string>([a.pkey])
|
|
109
|
+
const markFree = new Set<string>()
|
|
95
110
|
const isRegion = a.ptid === opts.regionPlacetypeID
|
|
96
111
|
|
|
112
|
+
const refused = (k: string): boolean => {
|
|
113
|
+
if (!isRegion) return false
|
|
114
|
+
const holder = official.get(`${a.cid}\0${k}`)
|
|
115
|
+
|
|
116
|
+
return typeof holder === "number" && holder !== id
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Returns 1 when it staged a row, so the caller adds the result to the count.
|
|
120
|
+
const stageMarkFree = (k: NameKey): number => {
|
|
121
|
+
const free = withoutApostropheLikeMarks(k)
|
|
122
|
+
|
|
123
|
+
if (!free || free === k || seen.has(free) || markFree.has(free) || refused(free)) return 0
|
|
124
|
+
markFree.add(free)
|
|
125
|
+
stageRow(free, a, id, 0)
|
|
126
|
+
|
|
127
|
+
return 1
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
nMarkFree += stageMarkFree(a.pkey as NameKey)
|
|
131
|
+
|
|
97
132
|
// The writer space-pads each separator and appends a trailing one, so every piece
|
|
98
133
|
// includes surrounding whitespace and the last one is empty.
|
|
99
134
|
// `normalizeLocalityForKey` folds both away.
|
|
100
|
-
for (const piece of alt
|
|
135
|
+
for (const piece of alt?.split(ALIAS_SEPARATOR) ?? []) {
|
|
101
136
|
const bare = opts.bareName?.(a.cid, piece.trim())
|
|
102
137
|
const keys = [normalizeLocalityForKey(piece), bare ? normalizeLocalityForKey(bare) : ""]
|
|
103
138
|
|
|
@@ -105,30 +140,35 @@ export function explodeAliasBags(
|
|
|
105
140
|
if (!k || seen.has(k)) continue
|
|
106
141
|
seen.add(k)
|
|
107
142
|
|
|
108
|
-
if (
|
|
109
|
-
|
|
143
|
+
if (refused(k)) {
|
|
144
|
+
regionOfficialRefused++
|
|
110
145
|
|
|
111
|
-
|
|
112
|
-
regionOfficialRefused++
|
|
113
|
-
|
|
114
|
-
continue
|
|
115
|
-
}
|
|
146
|
+
continue
|
|
116
147
|
}
|
|
117
148
|
|
|
118
|
-
|
|
149
|
+
// A mark-free form staged earlier now arrives as a name of its own, so it counts as one.
|
|
150
|
+
if (markFree.delete(k)) {
|
|
151
|
+
nMarkFree--
|
|
152
|
+
} else {
|
|
153
|
+
stageRow(k, a, id, 0)
|
|
154
|
+
}
|
|
119
155
|
|
|
120
156
|
if (position) {
|
|
121
157
|
nBare++
|
|
122
158
|
} else {
|
|
123
159
|
nAlias++
|
|
124
160
|
}
|
|
161
|
+
|
|
162
|
+
nMarkFree += stageMarkFree(k as NameKey)
|
|
125
163
|
}
|
|
126
164
|
}
|
|
127
165
|
|
|
128
|
-
|
|
166
|
+
if (alt) {
|
|
167
|
+
keyCounts.set(id, seen.size)
|
|
168
|
+
}
|
|
129
169
|
}
|
|
130
170
|
|
|
131
171
|
out.exec("COMMIT")
|
|
132
172
|
|
|
133
|
-
return { nAlias, nBare, keyCounts, regionOfficialRefused }
|
|
173
|
+
return { nAlias, nBare, nMarkFree, keyCounts, regionOfficialRefused }
|
|
134
174
|
}
|
|
@@ -8,10 +8,11 @@
|
|
|
8
8
|
*
|
|
9
9
|
* The join key is `(name_key, country, placetype)`, the same {@link normalizeLocalityForKey}
|
|
10
10
|
* the candidate build uses for its probe key, so the two sides fold identically.
|
|
11
|
-
*
|
|
12
|
-
*
|
|
11
|
+
* The score source is the importance build the candidate build matched to its
|
|
12
|
+
* admin database by md5 (`importance-source.ts`).
|
|
13
13
|
*
|
|
14
|
-
*
|
|
14
|
+
* The join stays on the name key rather than the id, the join every candidate build has used,
|
|
15
|
+
* so matching the two files changes which scores are read and leaves the join unchanged.
|
|
15
16
|
*
|
|
16
17
|
* The key by itself isn't enough.
|
|
17
18
|
* `(warwick, US, locality)` covers eleven different places.
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @file Extra folds a `candidate.db` applies to every `name_key`, recorded in the artifact so its reader
|
|
6
|
+
* folds each query key the same way.
|
|
7
|
+
*
|
|
8
|
+
* A fold changes which keys exist, so the build and the reader must agree on it. The build applies it
|
|
9
|
+
* as a post-pass over the materialized `candidate` table, and the reader reads the recorded folds once.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { DatabaseClient } from "@mailwoman/sqlite/client"
|
|
13
|
+
|
|
14
|
+
import type { CandidateDatabase } from "#candidate/schema"
|
|
15
|
+
import { hasTable } from "#sqlite-utils"
|
|
16
|
+
import { type NameKey, withArabicLetterVariantsFolded } from "#street/normalize"
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The table that lists the folds applied to the artifact's `name_key` column, one row per fold.
|
|
20
|
+
* An artifact without it applies none.
|
|
21
|
+
*/
|
|
22
|
+
export const CANDIDATE_KEY_FOLD_TABLE = "candidate_key_fold"
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The folds a candidate build can apply on top of `normalizeLocalityForKey`.
|
|
26
|
+
*/
|
|
27
|
+
export const CandidateKeyFold = {
|
|
28
|
+
/**
|
|
29
|
+
* {@link withArabicLetterVariantsFolded}: hamza, madda and vowel marks dropped,
|
|
30
|
+
* `ى` written `ي`, `ة` written `ه`.
|
|
31
|
+
*/
|
|
32
|
+
ArabicLetterVariants: "arabic-letter-variants",
|
|
33
|
+
} as const
|
|
34
|
+
|
|
35
|
+
export type CandidateKeyFold = (typeof CandidateKeyFold)[keyof typeof CandidateKeyFold]
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The key function of each fold, and the GLOB that selects the keys it can change.
|
|
39
|
+
*/
|
|
40
|
+
const FOLDS: Readonly<Record<CandidateKeyFold, { fold: (key: NameKey) => NameKey; glob: string }>> = {
|
|
41
|
+
[CandidateKeyFold.ArabicLetterVariants]: { fold: withArabicLetterVariantsFolded, glob: "*[-ۿ]*" },
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The counts {@link applyCandidateKeyFold} reports.
|
|
46
|
+
*/
|
|
47
|
+
export interface CandidateKeyFoldResult {
|
|
48
|
+
/**
|
|
49
|
+
* Rows whose key the fold changed.
|
|
50
|
+
*/
|
|
51
|
+
rekeyed: number
|
|
52
|
+
/**
|
|
53
|
+
* Rekeyed rows dropped because the folded key already held the same place under the same scope.
|
|
54
|
+
*/
|
|
55
|
+
merged: number
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Rewrites every `candidate.name_key` the fold changes and records the fold
|
|
60
|
+
* in {@link CANDIDATE_KEY_FOLD_TABLE}.
|
|
61
|
+
*
|
|
62
|
+
* A row whose folded key already exists for the same place, scope, placetype and rank is merged into it.
|
|
63
|
+
* It runs on a writable copy or inside a build, never on a published artifact.
|
|
64
|
+
*/
|
|
65
|
+
export async function applyCandidateKeyFold(
|
|
66
|
+
db: DatabaseClient<CandidateDatabase>,
|
|
67
|
+
foldName: CandidateKeyFold
|
|
68
|
+
): Promise<CandidateKeyFoldResult> {
|
|
69
|
+
const { fold, glob } = FOLDS[foldName]
|
|
70
|
+
const sqlName = `mw_key_fold_${foldName.replaceAll("-", "_")}`
|
|
71
|
+
|
|
72
|
+
db.function(sqlName, { deterministic: true }, (key) => fold(String(key) as NameKey))
|
|
73
|
+
|
|
74
|
+
const changed = `name_key GLOB '${glob}' AND ${sqlName}(name_key) <> name_key`
|
|
75
|
+
const { n: rekeyed } = db.prepare(`SELECT count(*) AS n FROM candidate WHERE ${changed}`).get() as { n: number }
|
|
76
|
+
|
|
77
|
+
db.exec("BEGIN")
|
|
78
|
+
|
|
79
|
+
const inserted = db
|
|
80
|
+
.prepare(
|
|
81
|
+
"INSERT OR IGNORE INTO candidate SELECT " +
|
|
82
|
+
`${sqlName}(name_key), country_id, region_id, placetype_id, neg_rank, spr_id, name, latitude, longitude, ` +
|
|
83
|
+
"min_lat, min_lon, max_lat, max_lon, population, is_primary, importance, name_role " +
|
|
84
|
+
`FROM candidate WHERE ${changed}`
|
|
85
|
+
)
|
|
86
|
+
.run()
|
|
87
|
+
|
|
88
|
+
db.prepare(`DELETE FROM candidate WHERE ${changed}`).run()
|
|
89
|
+
|
|
90
|
+
await db.schema
|
|
91
|
+
.createTable(CANDIDATE_KEY_FOLD_TABLE)
|
|
92
|
+
.ifNotExists()
|
|
93
|
+
.addColumn("fold", "text", (c) => c.primaryKey())
|
|
94
|
+
.execute()
|
|
95
|
+
|
|
96
|
+
db.prepare(`INSERT OR IGNORE INTO ${CANDIDATE_KEY_FOLD_TABLE} (fold) VALUES (?)`).run(foldName)
|
|
97
|
+
db.exec("COMMIT")
|
|
98
|
+
|
|
99
|
+
return { rekeyed, merged: rekeyed - Number(inserted.changes) }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The query-key function an artifact's recorded folds call for: identity when it records none.
|
|
104
|
+
*
|
|
105
|
+
* A fold name the reader doesn't know raises, because a key that misses that
|
|
106
|
+
* fold would miss every row the fold rewrote.
|
|
107
|
+
*/
|
|
108
|
+
export function candidateQueryKeyFold(db: DatabaseClient<CandidateDatabase>): (key: NameKey) => NameKey {
|
|
109
|
+
if (!hasTable(db, CANDIDATE_KEY_FOLD_TABLE)) return (key) => key
|
|
110
|
+
|
|
111
|
+
const names = (
|
|
112
|
+
db.prepare(`SELECT fold FROM ${CANDIDATE_KEY_FOLD_TABLE} ORDER BY fold`).all() as { fold: string }[]
|
|
113
|
+
).map((row) => row.fold)
|
|
114
|
+
|
|
115
|
+
const folds = names.map((name) => {
|
|
116
|
+
const known = FOLDS[name as CandidateKeyFold]
|
|
117
|
+
|
|
118
|
+
if (!known) throw new Error(`candidate.db records the key fold ${name}, which this reader doesn't implement`)
|
|
119
|
+
|
|
120
|
+
return known.fold
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
return (key) => {
|
|
124
|
+
let folded = key
|
|
125
|
+
|
|
126
|
+
for (const fold of folds) {
|
|
127
|
+
folded = fold(folded)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return folded
|
|
131
|
+
}
|
|
132
|
+
}
|
package/lib/candidate/lookup.ts
CHANGED
|
@@ -19,10 +19,11 @@ import {
|
|
|
19
19
|
type IntervalLabel,
|
|
20
20
|
} from "#candidate/ancestors/schema"
|
|
21
21
|
import { CANDIDATE_FTS_TABLE } from "#candidate/fts"
|
|
22
|
+
import { candidateQueryKeyFold } from "#candidate/key-fold"
|
|
22
23
|
import type { CandidateDatabase, CandidateTable, CountryCodeTable, PlacetypeCodeTable } from "#candidate/schema"
|
|
23
24
|
import { readGazetteerCoverageManifest } from "#coverage-manifest-schema"
|
|
24
25
|
import { POSTAL_CITY_CANDIDATE_TABLE, type PostalCityCandidateTable } from "#postal/city/candidate-schema"
|
|
25
|
-
import { rankByPrimaryPreference, type RankedRow, RERANK_FETCH } from "#primary-preference"
|
|
26
|
+
import { rankByPrimaryPreference, type RankedRow, regionAliasMargin, RERANK_FETCH } from "#primary-preference"
|
|
26
27
|
import { applyProximityRerank } from "#proximity-rerank"
|
|
27
28
|
import { REGION_CLASS_PLACETYPES, regionQualifierProbeKeys } from "#region-keys"
|
|
28
29
|
import { hasColumn, hasTable } from "#sqlite-utils"
|
|
@@ -133,6 +134,10 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
|
|
|
133
134
|
readonly #intervalCache = new Map<number, IntervalLabel | null>()
|
|
134
135
|
|
|
135
136
|
readonly #qualifierProbe: ReturnType<DatabaseClient["prepare"]> | undefined
|
|
137
|
+
/**
|
|
138
|
+
* The folds the artifact recorded for its `name_key` column, applied to every query key.
|
|
139
|
+
*/
|
|
140
|
+
readonly #queryKeyFold: (key: NameKey) => NameKey
|
|
136
141
|
/**
|
|
137
142
|
* Ancestor lineage accessor, nearest-first, present only when the artifact supports it.
|
|
138
143
|
*/
|
|
@@ -141,6 +146,8 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
|
|
|
141
146
|
constructor(opts: WOFCandidateTableLookupOpts) {
|
|
142
147
|
super(opts)
|
|
143
148
|
|
|
149
|
+
this.#queryKeyFold = candidateQueryKeyFold(this.database)
|
|
150
|
+
|
|
144
151
|
for (const r of allRows<CountryCodeTable>(this.database.prepare("SELECT id, code FROM country_codes"))) {
|
|
145
152
|
const code = String(r.code).toUpperCase()
|
|
146
153
|
this.#countryToID.set(code, Number(r.id))
|
|
@@ -246,7 +253,7 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
|
|
|
246
253
|
for (const key of regionQualifierProbeKeys(qualifier, country)) {
|
|
247
254
|
if (!key) continue
|
|
248
255
|
|
|
249
|
-
for (const row of allRows<{ spr_id: number }>(this.#qualifierProbe, key)) {
|
|
256
|
+
for (const row of allRows<{ spr_id: number }>(this.#qualifierProbe, this.#queryKeyFold(key as NameKey))) {
|
|
250
257
|
ids.add(Number(row.spr_id))
|
|
251
258
|
}
|
|
252
259
|
}
|
|
@@ -425,7 +432,8 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
|
|
|
425
432
|
text = text.replaceAll(/\s+/g, "")
|
|
426
433
|
}
|
|
427
434
|
|
|
428
|
-
const nameKey = normalizeLocalityForKey(text)
|
|
435
|
+
const nameKey = this.#queryKeyFold(normalizeLocalityForKey(text))
|
|
436
|
+
const strippedNameKey = this.#queryKeyFold(normalizeLocalityForKey(stripLocalityQualifier(text)))
|
|
429
437
|
|
|
430
438
|
if (!nameKey) return []
|
|
431
439
|
|
|
@@ -535,19 +543,19 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
|
|
|
535
543
|
|
|
536
544
|
const fetched = allRows<CandidateRow>(this.database.prepare(sql), ...params, Math.max(limit, RERANK_FETCH))
|
|
537
545
|
|
|
538
|
-
|
|
546
|
+
// Inside a stated region, an alias yields to a different place whose primary name equals
|
|
547
|
+
// the query, including an own-name variant the exemption spares from the worldwide penalty.
|
|
548
|
+
return regionID === null
|
|
549
|
+
? rankByPrimaryPreference(fetched, limit, undefined, this.#idToPlacetype, this.#variantAliasExemption)
|
|
550
|
+
: rankByPrimaryPreference(fetched, limit, regionAliasMargin, this.#idToPlacetype)
|
|
539
551
|
}
|
|
540
552
|
|
|
541
553
|
const cascade = (regionID: number | null): Array<RankedRow<CandidateRow>> => {
|
|
542
554
|
let rows = probe(nameKey, regionID)
|
|
543
555
|
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
if (strippedKey && strippedKey !== nameKey) {
|
|
548
|
-
// Stripped probes only accept primary rows to avoid alias-scrape matches.
|
|
549
|
-
rows = probe(strippedKey, regionID).filter((r) => r.is_primary === 1)
|
|
550
|
-
}
|
|
556
|
+
// Stripped probes only accept primary rows to avoid alias-scrape matches.
|
|
557
|
+
if (!rows.length && strippedNameKey && strippedNameKey !== nameKey) {
|
|
558
|
+
rows = probe(strippedNameKey, regionID).filter((r) => r.is_primary === 1)
|
|
551
559
|
}
|
|
552
560
|
|
|
553
561
|
// Typo-tolerant fallback for true name misses only, skipping postcodes.
|
|
@@ -573,7 +581,9 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
|
|
|
573
581
|
const hits = allRows<{ name_key: string }>(this.#ftsProbe, match, FUZZY_FETCH)
|
|
574
582
|
|
|
575
583
|
const ranked = hits
|
|
576
|
-
|
|
584
|
+
// An index built before the artifact's key folds holds unfolded keys, so each hit is folded too.
|
|
585
|
+
.map((h) => this.#queryKeyFold(String(h.name_key) as NameKey))
|
|
586
|
+
.map((nk) => ({ nk, s: wordFuzzySimilarity(nameKey, nk) }))
|
|
577
587
|
.filter((h) => h.s >= WORD_FUZZY_MIN && (hasCountryEvidence || h.nk[0] === nameKey[0]))
|
|
578
588
|
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
|
|
579
589
|
.sort((a, b) => b.s - a.s)
|
|
@@ -638,7 +648,7 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
|
|
|
638
648
|
// Admin-containment re-rank runs last.
|
|
639
649
|
const containmentOptions: ContainmentOptions = {
|
|
640
650
|
nameKey,
|
|
641
|
-
strippedKey:
|
|
651
|
+
strippedKey: strippedNameKey,
|
|
642
652
|
shapeFilters,
|
|
643
653
|
shapeParams,
|
|
644
654
|
limit,
|