SPB Git

Repository Public BSD-3-Clause

README.md 22.7 KB

# ORIXSearch

Offline search and geocoding for ORIX Maps: one SQLite file per map region (search.sqlite), built from OpenStreetMap data by Infrastructure/geocoder-builder and queried on the device. No network, no logging of queries or coordinates.

The package contains both sides, so that the on-disk schema is defined once:

  • the writer (SearchIndexWriter), used by the build tool on macOS;
  • the query engine (SearchEngine), used by the app on iOS 18 / macOS 15.

Dependencies: ORIXGeoCore and the system SQLite3 library (FTS5). No third-party code.

# Public API

# Engine (app side)

swift
public actor SearchEngine {
    public init()
    @discardableResult public func openIndex(at url: URL) throws -> SearchIndexInfo   // validates, opens read-only
    @discardableResult public func closeIndex(regionID: String) -> Bool
    public func closeAll()
    public var openIndexes: [SearchIndexInfo] { get }
    public nonisolated static func inspect(at url: URL) throws -> SearchIndexInfo       // metadata without keeping it open

    public func search(_ query: SearchQuery) async throws -> SearchResponse
    public func suggest(_ text: String, focus: Coordinate? = nil, viewport: BoundingBox? = nil, limit: Int = 8) async throws -> SearchResponse
    public func pointsOfInterest(categories: Set<PlaceCategory>, focus: Coordinate? = nil, viewport: BoundingBox? = nil, limit: Int = 50) async throws -> [SearchResult]
    public func pointsOfInterest(in box: BoundingBox, categories: Set<PlaceCategory>? = nil, limit: Int = 200) async throws -> [SearchResult]
    public func reverseGeocode(_ coordinate: Coordinate, maxDistance: Double = 150) async throws -> ReverseGeocodeOutcome
}

public struct SearchQuery: Sendable, Hashable, Codable {
    public enum Mode { case suggest, full }
    public init(text: String, mode: Mode = .full, focus: Coordinate? = nil, viewport: BoundingBox? = nil, limit: Int = 20,
                categories: Set<PlaceCategory>? = nil)
}

public struct SearchResponse: Sendable, Codable {
    public var parsed: ParsedQuery              // house number, street tokens, locality
    public var results: [SearchResult]          // best first
    public var matchedCategory: PlaceCategory?  // "essence" → .fuel
    public var corrections: [TermCorrection]    // typo corrections that were applied
    public var regionIDs: [String]
}

public struct SearchResult: Identifiable, Hashable, Sendable, Codable {
    public var id: String                       // "<region>/w123", "<region>/a/n456", "<region>/i/<way>/<number>", "coordinate:…"
    public var kind: SearchResultKind           // .coordinate, .place, .poi, .street, .address
    public var name: String                     // "" for an unnamed feature kept for its category, or a numbered road without a name
    public var category: PlaceCategory?         // points of interest
    public var placeType: PlaceType?            // places
    public var streetClass: StreetClass?        // streets
    public var houseNumber: String?, street: String?, district: String?, city: String?
    public var cityIsApproximate: Bool          // city = nearest settlement, not a boundary or a tag
    public var roadRef: String?                 // "40", "20;55"
    public var coordinate: Coordinate
    public var boundingBox: BoundingBox?        // streets and areas
    public var osm: OSMElementRef?              // element type + id
    public var regionID: String
    public var dataDate: Date?                  // date of the OSM data of the index
    public var addressMatch: AddressMatch?      // .exact, .sameNumberOtherSuffix, .withinTaggedRange, .interpolated, .streetOnly
    public var requestedHouseNumber: String?
    public var matchedBy: SearchMatchSource     // .name, .category, .address, .coordinate
    public var isTypoCorrected: Bool
    public var distance: Double?                // metres from the focus
    public var score: Double
    public var secondaryLine: String { get }    // "4545 Avenue Pierre-De Coubertin, Mercier–Hochelaga-Maisonneuve, Montréal"
}

public enum ReverseGeocodeOutcome: Sendable, Codable, Hashable {
    case found(ReverseGeocodeResult)            // .address, .street, .place: ReverseMatch? each with its distance; .nearest
    case nothingWithin(meters: Double)
}

public struct SearchIndexInfo: Sendable, Codable, Hashable   // regionID, schema version, boundingBox, dataDate, buildDate,
                                                             // attribution, builderVersion, counts by kind, fileURL
public enum SearchIndexError: Error, Equatable, Sendable     // fileNotFound, notASQLiteDatabase, corrupted, missingTable,
                                                             // missingMetadata, unsupportedSchemaVersion(found:supported:),
                                                             // fts5Unavailable, rtreeUnavailable, regionAlreadyOpen, writerMisuse, sqlite
public enum SQLiteCapabilities { static func verify() throws; static var hasRTree: Bool; static func verifyAll() throws; static var libraryVersion: String }

Typical use:

swift
let engine = SearchEngine()
try await engine.openIndex(at: regionDirectory.appendingPathComponent("search.sqlite"))

let task = Task { try await engine.suggest(text, focus: mapCentre, viewport: visibleBox) }
// When the user types another character: task.cancel(). The search stops (CancellationError).

let response = try await engine.search(SearchQuery(text: "1234 Sherbrooke O, Montréal", focus: userPosition))
if case .found(let here) = try await engine.reverseGeocode(tapped, maxDistance: 100) { … }

# Taxonomy

PlaceCategory (64 categories in 11 PlaceCategoryGroups) is the shared type for search, map filters and the Explorer: rawValue is the stable string identifier, code the stable integer stored in indexes, symbolName an SF Symbol, labelEN / labelFR / label(languageCode:) the bilingual labels, synonyms the search words ("essence", "station-service", "gas station"). PlaceCategory.matching(text:), suggestions(prefix:), classify(tags:) (OSM tags → category), isUsefulWithoutName. PlaceType (city … locality) and StreetClass (motorway … track) have the same shape. A test checks that every symbol name exists on the build machine (macOS 27, AppKit).

# Text

TextNormalizer (fold, rawTokens, canonicalTokens, canonicalKey, queryTokens, gluedArticleTokens, streetCoreKey), QueryParser.parse(_:lastIsPrefix:) -> ParsedQuery, EditDistance.bounded, TextScorer.score, Ranking.score, RoadReference.aliases, Importance.rank are public and pure, so the app and the tests can call them.

# Writer (build tool side)

swift
public final class SearchIndexWriter {
    public init(url: URL, regionID: String, options: Options = Options()) throws   // pageSize, geometryToleranceMeters, builderVersion, source
    public func addArea(name: String, level: AreaLevel) -> AreaID                  // .admin(level), .tagged, .nearestPlace
    public func add(_ place: PlaceRecord)
    public func add(_ poi: POIRecord)
    public func add(_ street: StreetRecord)                                        // geometry, addresses, interpolation ranges
    public func finish(boundingBox: BoundingBox? = nil, dataTimestamp: Date?, buildDate: Date = Date()) throws -> SearchIndexSummary
}

# How a query is answered

  1. Coordinates: if CoordinateText.parse accepts the text, a coordinate result comes first (works with no index open).
  2. Parsing: the part before the first comma is the name or street; a leading civic number ("1234", "1234A", "301-1234", "12 1/2") is split off, except for ordinal street names ("2e Avenue"); the part after the comma is the locality ("QC", "Canada" and postal codes are ignored). Without a comma, up to three trailing words that are the name of a locality of the index are also tried as the locality.
  3. Normalization (identical at build and query time): accents and case folded, split on anything that is not a letter or a digit, ordinals collapsed (1re → 1), road references merged (A-40 → a40), abbreviations mapped to one canonical token (av/ave → avenue, boul/blvd → boulevard, ch → chemin, rte → route, st/ste/saint/sainte/street → st, e/est/east, o/w/ouest/west, n/nord/north, s/sud/south, rd → road, dr/drive/docteur → dr, mtl → montreal…), articles dropped (de, du, la, the…), article + word also indexed glued ("La Fontaine" → lafontaine).
  4. Candidates come from FTS5 MATCH expressions: all words must be present (the last one as a prefix in type-ahead), optionally intersected with the kind/category, with the locality, and with the 3×3 block of coarse grid cells around the focus (5.5 km cells, then 44 km cells, then the whole index). Rows are stored by decreasing importance, so LIMIT keeps the most important matches of each stage.
  5. Categories: a text that is a category synonym lists that category nearest-first; "métro Berri-UQAM" searches the name among transit stations; brands ("SAQ") are not categories and go through the name search.
  6. Addresses: the street is searched like a name, then the number is resolved in that street's address blob: tagged number → .exact; same number, other suffix → .sameNumberOtherSuffix; inside a range tagged on one object ("1010-1014") → .withinTaggedRange; inside an OSM addr:interpolation range → .interpolated (position estimated along the interpolation way, flagged as such); otherwise the street itself, flagged .streetOnly with requestedHouseNumber set. No position is ever invented for a number that is not in the data.
  7. Typos: only when the query as typed returns fewer than 3 results (1 in type-ahead). Each word that is absent from the vocabulary is replaced by the vocabulary words within 1 edit (4–5 letters) or 2 edits (6+ letters, Damerau–Levenshtein), most frequent first; results are flagged isTypoCorrected and the response lists the corrections.
  8. Ranking: `0.55 × text + 0.20 × importance + proximity (≤ 0.25, ≤ 0.45 for category queries) + viewport (0.04)
    • locality match (0.15)`, plus a bonus for a resolved house number. Text: exact name 1.0 > name starts with the query ≈ 0.85 > query inside the name ≈ 0.7 > words in any order ≈ 0.6; a street type omitted in the query ("sherbrooke ouest" for "Rue Sherbrooke Ouest") does not count against a street. Importance: city > town > village > suburb …; points of interest get a little more with wikidata or a brand. Streets passing within about 0.8 km of the focus are measured to their geometry; farther ones are ranked between that bound and their representative point.
  9. Reverse geocoding returns the nearest real address point, the nearest street (distance to its geometry) and the nearest named place or point of interest within maxDistance (clamped to 1…2000 m), or .nothingWithin.

Cancellation: every public operation checks Task.isCancelled between stages and registers a cancellation handler that calls sqlite3_interrupt on the open connections, but only if the cancelled operation is the one running.

# Index schema (version 1.0)

Table Content
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
area(id, name, level) locality names; level = OSM admin level, 0 = addr:city tag, -1 = nearest settlement (approximation)
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
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>)
poi(cell, data) spatial grid (0.005° cells) of places and points of interest: entry id, kind, category, named flag, E7 position (delta-coded)
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
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)
vocab(term, df) name vocabulary (letters only, ≥ 3 characters) with document frequency

Opening validates: file exists, SQLite magic header, meta table, schema_major equal to 1 (otherwise unsupportedSchemaVersion), all tables present and readable, region_id present. Blob decoders are bounds-checked and report SearchIndexError.corrupted.

Spatial index: a grid instead of SQLite's R-tree. The first version used an rtree_i32 table for places and points of interest. On the Québec index it took 14.39 MiB (poi_rtree_node 11.32 + _rowid 2.98 + _parent 0.09, measured with dbstat); the grid blobs that replace it take 3.46 MiB and serve the same two lookups (nearest named entry, entries in a box). The index therefore needs FTS5 only. SQLiteCapabilities.verify() (called by the writer and at every open) fails with fts5Unavailable; hasRTree / verifyAll() report the R-tree module for diagnostics.

# Measured numbers

Machine: Mac with 18 cores and 48 GB, macOS 27.0, Swift 6.4.2, system SQLite 3.54.0, release build. Index: whole province of Québec (data/build/search/quebec/search.sqlite, 90 632 192 bytes, data timestamp 2026-11-24T21:21:23Z: 8 541 places, 275 157 points of interest, 134 053 streets, 1 488 538 addresses, 356 260 interpolation ranges). Build numbers are in Infrastructure/geocoder-builder/README.md.

Latency, orix-geocoder-bench --index … bench --rounds 10 (in Infrastructure/geocoder-builder), three runs, worst of the three:

Set Queries p50 p95 max Target
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
Suggestions (2–3 letter prefixes, partial addresses and names) 48 1.80 ms 14.90 ms 32.94 ms p95 < 50 ms: met
Reverse geocoding (150 m) 12 0.23 ms 0.47 ms 0.53 ms —

The first pass after opening the file gives the same percentiles as the warm passes (p95 3.52 ms and 15.12 ms); the file 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, 30 address blobs decoded) and "rue saint-d" (26 ms). These are timings on a desktop CPU; nothing was measured on an iPhone.

Size (4096-byte pages, after VACUUM), sqlite3 search.sqlite "select name, sum(pgsize) from dbstat group by name":

Part MiB Share
addr (1.49 M addresses, 356 k interpolation ranges) 26.50 31 %
entry (417 751 rows, names) 24.95 29 %
seg (street geometry, 296 745 cells) 19.64 23 %
fts 10.72 12 %
poi 3.46 4 %
vocab, area, meta 1.15 1 %
Total 86.4

zip -9 of the file: 62 506 210 bytes (59.6 MiB). What was tried, each measured with dbstat on a full province build: R-tree → grid (14.39 → 3.46 MiB); packed entry columns (27.65 → 24.95 MiB); seg with street-id deltas and coordinates chained from the cell corner, in E7 instead of the E6 of the first version to follow the repository convention (20.79 → 19.64 MiB, the two changes together); addr with chained interpolation lines (33.63 → 31.60 MiB), then order-free signed deltas keeping the smaller of "by number" and "by OSM id" (→ 26.52 MiB); page size 8192 / 16384 (85.5 → 84.2 / 83.5 MiB on the build of that moment: −1.5 % / −2.3 %, not worth leaving the default 4096). The FTS table was contentless with detail=column and no column sizes from the start. FTS5 prefix= indexes were not needed for the latency target and were not added. The first complete build was 107.4 MiB.

Sanity results on the province index (orix-geocoder-bench --index … sanity, focus = 45.5088,-73.5878 for Montréal queries and 46.8131,-71.2075 for Québec City queries):

Query First results
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
99999 rue Sherbrooke Ouest Rue Sherbrooke Ouest — Montréal street_only (number not found), then Westmount, Montréal-Ouest; no address
1234 Sherbrooke O, Montréal 1234 Rue Sherbrooke Ouest — Montréal address:interpolated (way 1291428919, 45.49971,-73.57833)
Stade olympique Stade olympique — 4545 Avenue Pierre-De Coubertin, Mercier–Hochelaga-Maisonneuve, Montréal (w108505523)
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.
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
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
essence near Québec City Esso 459 m, Petro-Canada 539 m, Ultramar 1658 m, Esso (355 3e Avenue) 1745 m
SAQ near Montréal four "SAQ" liquor_store at 1013–1381 m (name search, no category)
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
sherbroke near Montréal corrected to "sherbrooke": Sherbrooke (métro station, 1893 m), Sherbrooke (city), Rue Sherbrooke Ouest — Montréal
montreel corrected to "montreal": Montréal (city), Montréal-Ouest, Montréal-Est
45.5017, -73.5673 coordinate result
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
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
reverse 52.0,-72.0 nothing within 150 m

# Tests

text
swift test                                                   # 67 tests in 10 suites; 2 are opt-in and skipped without the variable
ORIX_SEARCH_INDEX=/abs/path/data/build/search/quebec/search.sqlite swift test
ORIX_SEARCH_INDEX=… swift test -c release -Xswiftc -enable-testing   # latency targets on optimized code

Run on 2026-11-25: 0 failed. Without the variable the run reports 67 tests passed, the 2 tests of RealIndexTests being skipped (65 executed); with it, all 67 are executed and pass, in debug and in release. Parameterized tests count once. Covered: normalization, abbreviations, tokenization, ordinals, references, query parsing, text scoring and ranking, edit distance, taxonomy (unique stable codes, synonyms, OSM mapping, SF Symbol names), blob codecs (round trip, every truncation, random bytes, bit flips), end-to-end index built in memory through the writer (names, abbreviations, addresses of every match class, street-only, localities, categories, ranking, typos, suggestions, coordinates, reverse geocoding, box queries, multi-region merge, close/replace/reopen, Codable), schema and version validation, non-SQLite / foreign / truncated / randomly damaged files, corrupted blobs, cancellation (before start and sqlite3_interrupt of a running statement).

The library also compiles for iOS: swift build -c release --triple arm64-apple-ios18.0 --sdk "$(xcrun --sdk iphoneos --show-sdk-path)" completed on 2026-11-25. It was not run on a device or a simulator.

# Known limits

  • Ranking follows "exact name > prefix > partial" strictly: a minor object whose name is exactly the query outranks a famous one whose name only contains it (the Château Frontenac case above).
  • Typo correction assumes the first letter is right, corrects only words absent from the vocabulary, and does not correct the locality part. A wrong word that happens to exist is not corrected.
  • Languages: the display name is name (else name:fr, name:en, brand); the other variants are searchable but the engine does not pick a display language. The normalization vocabulary is French and English as used in Québec.
  • Street distance: exact only within about 0.8 km of the focus (0.4 km in type-ahead); beyond, distance is the distance to the street's representative point.
  • One street, several lines: a street is one entry per municipality and per connected group; identical name + city are merged in the result list, but the same street in two municipalities gives two lines.
  • Addresses take the locality of their street entry (boundary-based), not their own addr:city; postal codes and unit numbers are not indexed; a street known only from addr:street tags has no geometry.
  • Interpolated addresses are estimates along the OSM interpolation way; addr:inclusion is ignored; they are never returned by reverse geocoding (only real address points are).
  • Reverse geocoding does not return the containing municipality on its own; the city comes with the street or address match. Maximum radius 2000 m.
  • Regions: results of overlapping regions are de-duplicated by OSM element; streets cut by a region border are not merged.
  • A region index is opened read-only with one connection; replacing the file requires closeIndex first.

# Not done

  • Not run on iOS (device or simulator): availability of FTS5 in the iOS system SQLite, memory use and latency on a phone are unverified. SQLiteCapabilities.verify() will report a missing FTS5 at the first open.
  • No measurement with a cold file cache, and none of memory use of the engine.
  • No transliteration or search in scripts other than Latin beyond plain token matching (Inuktitut syllabics are indexed as written).
  • No phonetic matching, no synonym expansion between street types ("rue" vs "avenue"), no ranking from usage or history.
  • No "search along a route", no opening hours, no postal-code search.
  • No incremental update of an index: a region is rebuilt and replaced.
  • Format documentation in docs/ (the schema is documented here and in Schema.swift; docs/ belongs to the lead).
Files main
Menu

Theme