Repository Public BSD-3-Clause
1# ORIXSearch23Offline search and geocoding for ORIX Maps: one SQLite file per map region (`search.sqlite`), built from OpenStreetMap4data by `Infrastructure/geocoder-builder` and queried on the device. No network, no logging of queries or coordinates.56The package contains both sides, so that the on-disk schema is defined once:78- the **writer** (`SearchIndexWriter`), used by the build tool on macOS;9- the **query engine** (`SearchEngine`), used by the app on iOS 18 / macOS 15.1011Dependencies: `ORIXGeoCore` and the system `SQLite3` library (FTS5). No third-party code.1213## Public API1415### Engine (app side)1617```swift18public actor SearchEngine {19 public init()20 @discardableResult public func openIndex(at url: URL) throws -> SearchIndexInfo // validates, opens read-only21 @discardableResult public func closeIndex(regionID: String) -> Bool22 public func closeAll()23 public var openIndexes: [SearchIndexInfo] { get }24 public nonisolated static func inspect(at url: URL) throws -> SearchIndexInfo // metadata without keeping it open2526 public func search(_ query: SearchQuery) async throws -> SearchResponse27 public func suggest(_ text: String, focus: Coordinate? = nil, viewport: BoundingBox? = nil, limit: Int = 8) async throws -> SearchResponse28 public func pointsOfInterest(categories: Set<PlaceCategory>, focus: Coordinate? = nil, viewport: BoundingBox? = nil, limit: Int = 50) async throws -> [SearchResult]29 public func pointsOfInterest(in box: BoundingBox, categories: Set<PlaceCategory>? = nil, limit: Int = 200) async throws -> [SearchResult]30 public func reverseGeocode(_ coordinate: Coordinate, maxDistance: Double = 150) async throws -> ReverseGeocodeOutcome31}3233public struct SearchQuery: Sendable, Hashable, Codable {34 public enum Mode { case suggest, full }35 public init(text: String, mode: Mode = .full, focus: Coordinate? = nil, viewport: BoundingBox? = nil, limit: Int = 20,36 categories: Set<PlaceCategory>? = nil)37}3839public struct SearchResponse: Sendable, Codable {40 public var parsed: ParsedQuery // house number, street tokens, locality41 public var results: [SearchResult] // best first42 public var matchedCategory: PlaceCategory? // "essence" → .fuel43 public var corrections: [TermCorrection] // typo corrections that were applied44 public var regionIDs: [String]45}4647public struct SearchResult: Identifiable, Hashable, Sendable, Codable {48 public var id: String // "<region>/w123", "<region>/a/n456", "<region>/i/<way>/<number>", "coordinate:…"49 public var kind: SearchResultKind // .coordinate, .place, .poi, .street, .address50 public var name: String // "" for an unnamed feature kept for its category, or a numbered road without a name51 public var category: PlaceCategory? // points of interest52 public var placeType: PlaceType? // places53 public var streetClass: StreetClass? // streets54 public var houseNumber: String?, street: String?, district: String?, city: String?55 public var cityIsApproximate: Bool // city = nearest settlement, not a boundary or a tag56 public var roadRef: String? // "40", "20;55"57 public var coordinate: Coordinate58 public var boundingBox: BoundingBox? // streets and areas59 public var osm: OSMElementRef? // element type + id60 public var regionID: String61 public var dataDate: Date? // date of the OSM data of the index62 public var addressMatch: AddressMatch? // .exact, .sameNumberOtherSuffix, .withinTaggedRange, .interpolated, .streetOnly63 public var requestedHouseNumber: String?64 public var matchedBy: SearchMatchSource // .name, .category, .address, .coordinate65 public var isTypoCorrected: Bool66 public var distance: Double? // metres from the focus67 public var score: Double68 public var secondaryLine: String { get } // "4545 Avenue Pierre-De Coubertin, Mercier–Hochelaga-Maisonneuve, Montréal"69}7071public enum ReverseGeocodeOutcome: Sendable, Codable, Hashable {72 case found(ReverseGeocodeResult) // .address, .street, .place: ReverseMatch? each with its distance; .nearest73 case nothingWithin(meters: Double)74}7576public struct SearchIndexInfo: Sendable, Codable, Hashable // regionID, schema version, boundingBox, dataDate, buildDate,77 // attribution, builderVersion, counts by kind, fileURL78public enum SearchIndexError: Error, Equatable, Sendable // fileNotFound, notASQLiteDatabase, corrupted, missingTable,79 // missingMetadata, unsupportedSchemaVersion(found:supported:),80 // fts5Unavailable, rtreeUnavailable, regionAlreadyOpen, writerMisuse, sqlite81public enum SQLiteCapabilities { static func verify() throws; static var hasRTree: Bool; static func verifyAll() throws; static var libraryVersion: String }82```8384Typical use:8586```swift87let engine = SearchEngine()88try await engine.openIndex(at: regionDirectory.appendingPathComponent("search.sqlite"))8990let task = Task { try await engine.suggest(text, focus: mapCentre, viewport: visibleBox) }91// When the user types another character: task.cancel(). The search stops (CancellationError).9293let response = try await engine.search(SearchQuery(text: "1234 Sherbrooke O, Montréal", focus: userPosition))94if case .found(let here) = try await engine.reverseGeocode(tapped, maxDistance: 100) { … }95```9697### Taxonomy9899`PlaceCategory` (64 categories in 11 `PlaceCategoryGroup`s) is the shared type for search, map filters and the Explorer:100`rawValue` is the stable string identifier, `code` the stable integer stored in indexes, `symbolName` an SF Symbol,101`labelEN` / `labelFR` / `label(languageCode:)` the bilingual labels, `synonyms` the search words ("essence",102"station-service", "gas station"). `PlaceCategory.matching(text:)`, `suggestions(prefix:)`, `classify(tags:)` (OSM tags →103category), `isUsefulWithoutName`. `PlaceType` (city … locality) and `StreetClass` (motorway … track) have the same104shape. A test checks that every symbol name exists on the build machine (macOS 27, AppKit).105106### Text107108`TextNormalizer` (`fold`, `rawTokens`, `canonicalTokens`, `canonicalKey`, `queryTokens`, `gluedArticleTokens`,109`streetCoreKey`), `QueryParser.parse(_:lastIsPrefix:) -> ParsedQuery`, `EditDistance.bounded`, `TextScorer.score`,110`Ranking.score`, `RoadReference.aliases`, `Importance.rank` are public and pure, so the app and the tests can call them.111112### Writer (build tool side)113114```swift115public final class SearchIndexWriter {116 public init(url: URL, regionID: String, options: Options = Options()) throws // pageSize, geometryToleranceMeters, builderVersion, source117 public func addArea(name: String, level: AreaLevel) -> AreaID // .admin(level), .tagged, .nearestPlace118 public func add(_ place: PlaceRecord)119 public func add(_ poi: POIRecord)120 public func add(_ street: StreetRecord) // geometry, addresses, interpolation ranges121 public func finish(boundingBox: BoundingBox? = nil, dataTimestamp: Date?, buildDate: Date = Date()) throws -> SearchIndexSummary122}123```124125## How a query is answered1261271. **Coordinates**: if `CoordinateText.parse` accepts the text, a coordinate result comes first (works with no index open).1282. **Parsing**: the part before the first comma is the name or street; a leading civic number ("1234", "1234A",129 "301-1234", "12 1/2") is split off, except for ordinal street names ("2e Avenue"); the part after the comma is the130 locality ("QC", "Canada" and postal codes are ignored). Without a comma, up to three trailing words that are the name131 of a locality of the index are also tried as the locality.1323. **Normalization** (identical at build and query time): accents and case folded, split on anything that is not a133 letter or a digit, ordinals collapsed (1re → 1), road references merged (A-40 → `a40`), abbreviations mapped to one134 canonical token (av/ave → avenue, boul/blvd → boulevard, ch → chemin, rte → route, st/ste/saint/sainte/street → `st`,135 e/est/east, o/w/ouest/west, n/nord/north, s/sud/south, rd → road, dr/drive/docteur → `dr`, mtl → montreal…),136 articles dropped (de, du, la, the…), article + word also indexed glued ("La Fontaine" → `lafontaine`).1374. **Candidates** come from FTS5 `MATCH` expressions: all words must be present (the last one as a prefix in type-ahead),138 optionally intersected with the kind/category, with the locality, and with the 3×3 block of coarse grid cells around139 the focus (5.5 km cells, then 44 km cells, then the whole index). Rows are stored by decreasing importance, so `LIMIT`140 keeps the most important matches of each stage.1415. **Categories**: a text that is a category synonym lists that category nearest-first; "métro Berri-UQAM" searches the142 name among transit stations; brands ("SAQ") are not categories and go through the name search.1436. **Addresses**: the street is searched like a name, then the number is resolved in that street's address blob:144 tagged number → `.exact`; same number, other suffix → `.sameNumberOtherSuffix`; inside a range tagged on one object145 ("1010-1014") → `.withinTaggedRange`; inside an OSM `addr:interpolation` range → `.interpolated` (position estimated146 along the interpolation way, flagged as such); otherwise **the street itself, flagged `.streetOnly`** with147 `requestedHouseNumber` set. No position is ever invented for a number that is not in the data.1487. **Typos**: only when the query as typed returns fewer than 3 results (1 in type-ahead). Each word that is absent from149 the vocabulary is replaced by the vocabulary words within 1 edit (4–5 letters) or 2 edits (6+ letters,150 Damerau–Levenshtein), most frequent first; results are flagged `isTypoCorrected` and the response lists the corrections.1518. **Ranking**: `0.55 × text + 0.20 × importance + proximity (≤ 0.25, ≤ 0.45 for category queries) + viewport (0.04)152 + locality match (0.15)`, plus a bonus for a resolved house number. Text: exact name 1.0 > name starts with the query153 ≈ 0.85 > query inside the name ≈ 0.7 > words in any order ≈ 0.6; a street type omitted in the query ("sherbrooke154 ouest" for "Rue Sherbrooke Ouest") does not count against a street. Importance: city > town > village > suburb …;155 points of interest get a little more with wikidata or a brand. Streets passing within about 0.8 km of the focus156 are measured to their geometry; farther ones are ranked between that bound and their representative point.1579. **Reverse geocoding** returns the nearest real address point, the nearest street (distance to its geometry) and the158 nearest named place or point of interest within `maxDistance` (clamped to 1…2000 m), or `.nothingWithin`.159160Cancellation: every public operation checks `Task.isCancelled` between stages and registers a cancellation handler161that calls `sqlite3_interrupt` on the open connections, but only if the cancelled operation is the one running.162163## Index schema (version 1.0)164165| Table | Content |166| --- | --- |167| `meta(key, value)` | `schema_major`, `schema_minor`, `region_id`, `bbox` (minLon,minLat,maxLon,maxLat), `data_timestamp` (ISO 8601, empty when the extract has none), `build_date`, `attribution` ("© OpenStreetMap contributors (ODbL)"), `builder_version`, `source`, `count_place`, `count_poi`, `count_street`, `count_address`, `count_interpolation` |168| `area(id, name, level)` | locality names; `level` = OSM admin level, 0 = `addr:city` tag, -1 = nearest settlement (approximation) |169| `entry(id, meta, osm, lat, lon, name, alt, city, district, hn, street, ref, box)` | one row per place, point of interest or street; `id` = importance order; `meta` = kind (2 bits) + code (8) + rank (7) + flags; `osm` = id × 4 + type; `lat`/`lon` E7; `alt` = name variants separated by U+001F; `box` = 4 × Int32 LE E7 |170| `fts` | FTS5, contentless, `detail=column`, `columnsize=0`: `name` (canonical tokens of all variants and reference aliases), `cat` (`k<kind>`, `c<category>`), `geo` (`a…`/`b…` grid cells, `y<area id>`) |171| `poi(cell, data)` | spatial grid (0.005° cells) of places and points of interest: entry id, kind, category, named flag, E7 position (delta-coded) |172| `seg(cell, data)` | street geometry per 0.005° cell (Douglas–Peucker 2 m, E7 delta-coded), plus markers for cells where a street has addresses but no geometry |173| `addr(street, data)` | per street: house numbers (number, text when not plain, E7 position, OSM element) and interpolation ranges (start, end, step, way id, line) |174| `vocab(term, df)` | name vocabulary (letters only, ≥ 3 characters) with document frequency |175176Opening validates: file exists, SQLite magic header, `meta` table, `schema_major` equal to 1 (otherwise177`unsupportedSchemaVersion`), all tables present and readable, `region_id` present. Blob decoders are bounds-checked and178report `SearchIndexError.corrupted`.179180**Spatial index: a grid instead of SQLite's R-tree.** The first version used an `rtree_i32` table for places and points181of interest. On the Québec index it took 14.39 MiB (`poi_rtree_node` 11.32 + `_rowid` 2.98 + `_parent` 0.09, measured182with `dbstat`); the grid blobs that replace it take 3.46 MiB and serve the same two lookups (nearest named entry, entries183in a box). The index therefore needs FTS5 only. `SQLiteCapabilities.verify()` (called by the writer and at every open)184fails with `fts5Unavailable`; `hasRTree` / `verifyAll()` report the R-tree module for diagnostics.185186## Measured numbers187188Machine: Mac with 18 cores and 48 GB, macOS 27.0, Swift 6.4.2, system SQLite 3.54.0, release build. Index: whole189province of Québec (`data/build/search/quebec/search.sqlite`, 90 632 192 bytes, data timestamp 2026-11-24T21:21:23Z:1908 541 places, 275 157 points of interest, 134 053 streets, 1 488 538 addresses, 356 260 interpolation ranges). Build191numbers are in `Infrastructure/geocoder-builder/README.md`.192193Latency, `orix-geocoder-bench --index … bench --rounds 10` (in `Infrastructure/geocoder-builder`), three runs, worst of the three:194195| Set | Queries | p50 | p95 | max | Target |196| --- | --- | --- | --- | --- | --- |197| Full search (names, addresses with and without number, categories near a point, typos, references) | 44 | 1.08 ms | 3.50 ms | 4.18 ms | p95 < 150 ms: met |198| Suggestions (2–3 letter prefixes, partial addresses and names) | 48 | 1.80 ms | 14.90 ms | 32.94 ms | p95 < 50 ms: met |199| Reverse geocoding (150 m) | 12 | 0.23 ms | 0.47 ms | 0.53 ms | — |200201The first pass after opening the file gives the same percentiles as the warm passes (p95 3.52 ms and 15.12 ms); the202file was in the OS cache, a cold read from flash was not measured. The slowest queries are type-ahead addresses with a one-letter street ("1000 r": 33–37 ms,20330 address blobs decoded) and "rue saint-d" (26 ms). These are timings on a desktop CPU; nothing was measured on an iPhone.204205Size (4096-byte pages, after `VACUUM`), `sqlite3 search.sqlite "select name, sum(pgsize) from dbstat group by name"`:206207| Part | MiB | Share |208| --- | --- | --- |209| `addr` (1.49 M addresses, 356 k interpolation ranges) | 26.50 | 31 % |210| `entry` (417 751 rows, names) | 24.95 | 29 % |211| `seg` (street geometry, 296 745 cells) | 19.64 | 23 % |212| `fts` | 10.72 | 12 % |213| `poi` | 3.46 | 4 % |214| `vocab`, `area`, `meta` | 1.15 | 1 % |215| Total | 86.4 | |216217`zip -9` of the file: 62 506 210 bytes (59.6 MiB). What was tried, each measured with `dbstat` on a full province218build: R-tree → grid (14.39 → 3.46 MiB); packed `entry` columns (27.65 → 24.95 MiB); `seg` with street-id deltas and219coordinates chained from the cell corner, in E7 instead of the E6 of the first version to follow the repository220convention (20.79 → 19.64 MiB, the two changes together); `addr` with chained interpolation lines (33.63 → 31.60 MiB),221then order-free signed deltas keeping the smaller of "by number" and "by OSM id" (→ 26.52 MiB); page size 8192 / 16384222(85.5 → 84.2 / 83.5 MiB on the build of that moment: −1.5 % / −2.3 %, not worth leaving the default 4096). The FTS223table was contentless with `detail=column` and no column sizes from the start. FTS5 `prefix=` indexes were not needed224for the latency target and were not added. The first complete build was 107.4 MiB.225226Sanity results on the province index (`orix-geocoder-bench --index … sanity`, focus = 45.5088,-73.5878 for Montréal227queries and 46.8131,-71.2075 for Québec City queries):228229| Query | First results |230| --- | --- |231| `1000 rue Sherbrooke Ouest` | **1000 Rue Sherbrooke Ouest — Montréal** `address:exact` (n7508424280, 45.50289,-73.57513), a second object with the same address 45 m away (n14382033801), then Rue Sherbrooke Ouest of Westmount / Montréal-Ouest as `street_only` |232| `99999 rue Sherbrooke Ouest` | **Rue Sherbrooke Ouest — Montréal** `street_only` (number not found), then Westmount, Montréal-Ouest; no address |233| `1234 Sherbrooke O, Montréal` | **1234 Rue Sherbrooke Ouest — Montréal** `address:interpolated` (way 1291428919, 45.49971,-73.57833) |234| `Stade olympique` | **Stade olympique — 4545 Avenue Pierre-De Coubertin, Mercier–Hochelaga-Maisonneuve, Montréal** (w108505523) |235| `Château Frontenac` | 1. "Château Frontenac", a bike-share station of that exact name (n12646643435); 2. **Fairmont Le Château Frontenac — 1 Rue des Carrières, La Cité-Limoilou, Québec** (r32580). The hotel is second because the station's name is the exact text. |236| `café` near 45.5088,-73.5878 | Café des amis du belvédère 547 m, The Yellow Door 753 m, Gerts Café 934 m, Santropol 943 m, Dispatch Coffee 950 m, Edmond Café Cantine 958 m |237| `pharmacie` near Québec City | Proxim 820 m, Pharmaprix (698 Rue Saint-Jean) 911 m, Brunet 1095 m, Uniprix 1331 m, Jean Coutu 1437 m, Familiprix 1690 m |238| `essence` near Québec City | Esso 459 m, Petro-Canada 539 m, Ultramar 1658 m, Esso (355 3e Avenue) 1745 m |239| `SAQ` near Montréal | four "SAQ" `liquor_store` at 1013–1381 m (name search, no category) |240| `A-40` near Montréal | Autoroute Métropolitaine — Montréal (ref 40), — Mont-Royal (ref 15;40), Autoroute Félix-Leclerc — Mont-Royal, — Montréal |241| `sherbroke` near Montréal | corrected to "sherbrooke": Sherbrooke (métro station, 1893 m), Sherbrooke (city), Rue Sherbrooke Ouest — Montréal |242| `montreel` | corrected to "montreal": Montréal (city), Montréal-Ouest, Montréal-Est |243| `45.5017, -73.5673` | coordinate result |244| reverse 45.5017,-73.5673 (150 m) | address **700 Boulevard René-Lévesque Ouest — Montréal** at 24 m; street **Boulevard Robert-Bourassa** at 6 m; place "Vargas" (restaurant) at 25 m |245| reverse 46.8119,-71.2052 | address 1 Rue des Carrières at 35 m; street Rue des Carrières at 19 m; place Fairmont Le Château Frontenac at 22 m |246| reverse 52.0,-72.0 | nothing within 150 m |247248## Tests249250```251swift test # 67 tests in 10 suites; 2 are opt-in and skipped without the variable252ORIX_SEARCH_INDEX=/abs/path/data/build/search/quebec/search.sqlite swift test253ORIX_SEARCH_INDEX=… swift test -c release -Xswiftc -enable-testing # latency targets on optimized code254```255256Run on 2026-11-25: 0 failed. Without the variable the run reports 67 tests passed, the 2 tests of `RealIndexTests`257being skipped (65 executed); with it, all 67 are executed and pass, in debug and in release. Parameterized tests count once.258Covered: normalization, abbreviations, tokenization, ordinals, references, query parsing, text scoring and ranking,259edit distance, taxonomy (unique stable codes, synonyms, OSM mapping, SF Symbol names), blob codecs (round trip, every260truncation, random bytes, bit flips), end-to-end index built in memory through the writer (names, abbreviations,261addresses of every match class, street-only, localities, categories, ranking, typos, suggestions, coordinates,262reverse geocoding, box queries, multi-region merge, close/replace/reopen, Codable), schema and version validation,263non-SQLite / foreign / truncated / randomly damaged files, corrupted blobs, cancellation (before start and264`sqlite3_interrupt` of a running statement).265266The library also compiles for iOS: `swift build -c release --triple arm64-apple-ios18.0 --sdk "$(xcrun --sdk iphoneos --show-sdk-path)"`267completed on 2026-11-25. It was not run on a device or a simulator.268269## Known limits270271- **Ranking** follows "exact name > prefix > partial" strictly: a minor object whose name is exactly the query outranks a272 famous one whose name only contains it (the Château Frontenac case above).273- **Typo correction** assumes the first letter is right, corrects only words absent from the vocabulary, and does not274 correct the locality part. A wrong word that happens to exist is not corrected.275- **Languages**: the display name is `name` (else `name:fr`, `name:en`, `brand`); the other variants are searchable but276 the engine does not pick a display language. The normalization vocabulary is French and English as used in Québec.277- **Street distance**: exact only within about 0.8 km of the focus (0.4 km in type-ahead); beyond, `distance` is the278 distance to the street's representative point.279- **One street, several lines**: a street is one entry per municipality and per connected group; identical name + city280 are merged in the result list, but the same street in two municipalities gives two lines.281- **Addresses** take the locality of their street entry (boundary-based), not their own `addr:city`; postal codes and282 unit numbers are not indexed; a street known only from `addr:street` tags has no geometry.283- **Interpolated addresses** are estimates along the OSM interpolation way; `addr:inclusion` is ignored; they are never284 returned by reverse geocoding (only real address points are).285- **Reverse geocoding** does not return the containing municipality on its own; the city comes with the street or286 address match. Maximum radius 2000 m.287- **Regions**: results of overlapping regions are de-duplicated by OSM element; streets cut by a region border are not merged.288- A region index is opened read-only with one connection; replacing the file requires `closeIndex` first.289290## Not done291292- Not run on iOS (device or simulator): availability of FTS5 in the iOS system SQLite, memory use and latency on a293 phone are unverified. `SQLiteCapabilities.verify()` will report a missing FTS5 at the first open.294- No measurement with a cold file cache, and none of memory use of the engine.295- No transliteration or search in scripts other than Latin beyond plain token matching (Inuktitut syllabics are296 indexed as written).297- No phonetic matching, no synonym expansion between street types ("rue" vs "avenue"), no ranking from usage or history.298- No "search along a route", no opening hours, no postal-code search.299- No incremental update of an index: a region is rebuilt and replaced.300- Format documentation in `docs/` (the schema is documented here and in `Schema.swift`; `docs/` belongs to the lead).301