Modern Apps git

← Modern-Apps.git

maps: search folds apostrophes and accents ("mcdonalds", "cafe") (#mapsearch)

Commit
85e56c74065b93b8442533819b7c41ef60e1cb4f
Author
Vayun Mathur <[email protected]>
When
2026-11-13 20:30 UTC (22 days ago)
Parents
422ffc4
Symptom: from Union Square, SF, "mcdonalds" returned only places
1,377-4,184 km away, though there is a McDonald's 150 m from the
search centre; in Paris "musee" returned museums 63-411 km away and
"cafe" missed every "Café …" in the 1er.

Root cause: poi_name_index.bin is sorted by raw UTF-8 with only ASCII
A-Z folded (the cross-language contract in poi_side.rs). OSM spells
the brand "McDonald's" and the museum "Musée", so the words the user
types are simply not prefixes of the indexed words: the 139 entries
that do start with "mcdonalds" are all far away, and no word starts
with "musee". The index cannot be refolded without a format change, so
the lookup tries the spellings instead:

* possessives: a token ending in "s" is also looked up as "…'s" and
  "…’s"; a typed apostrophe is also looked up without it;
* an accented token is also looked up with its accents folded
  ("café" -> "cafe");
* one-accent variants: each ASCII letter that commonly carries an
  accent is tried with its most frequent accented forms in planet4's
  names (é 658 k, ó 341 k, á 327 k, í 315 k, ü 249 k, ä 226 k, ö 194 k,
  è 144 k, ç 120 k, ñ 87 k), one position at a time, plus É/Á/Ö as a
  first letter (only ASCII is case-folded in the index). Tokens under
  3 letters skip this.

All spellings' ranges feed the same candidate scan. PoiSearch.normalize
(used to re-match and rank the returned names) now deletes apostrophes
instead of turning them into spaces, so "McDonald's" and "mcdonalds"
normalise alike, and exposes foldDiacritics.

Cost: every variant is one more binary search over the word index; an
empty one is settled with a single probe after it. Measured cold with
the page tracer (SF): "pizza" 122 -> 333 128-KiB windows, "starbucks"
97 -> 266; warm time unchanged (2-6 ms). Still ~20x below the old
engine (5,995 / 2,178), and it is what makes "cafe"/"musee"/"ecole"
work in France, Spain, Germany. (Variants were measured at full Latin-1
coverage first: ~2x this cost for little extra recall, hence the
frequency-trimmed list.)

Before -> after (top hits):
  SF  mcdonalds  McDonalds Landing Regional Park 1,377 km
                 -> McDonald's 0.15 km, McDonald's 0.54 km, ...
  SF  peets      -> Peet's Coffee 0.30 km, ...
  Paris musee    Musee de mécanique naturelle 63.8 km, ...
                 -> Musée du Louvre 0.19 km, Musée en Herbe 0.33 km
  Paris ecole    Ecole (village) 391 km first -> École … 0.32 km
  Paris cafe     Cafe Piadine 0.78 km -> Café Richelieu 0.15 km

Tests: PoiIndexSmartTest gains "possessives and accents match either
way round"; POI unit tests and the real-archive test pass standalone.

Diff

maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.ktindex c61b920d8d..4d364c3492 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWordSearch.kt@@ -17,17 +17,21 @@ package com.vayunmathur.maps.util  private const val BYTE_MASK = 0xFF +/** Shortest token whose possessive ("joes" -> "joe's") is looked up too. */+private const val POSSESSIVE_MIN_LEN = 3+ /** How often (in entries) a long scan polls its cancel token. */ private const val SCAN_POLL_MASK = 0xFFFF  /** Entries `[first, last]` whose word starts with [key]; empty when none. */-internal fun PoiIndex.Mapped.prefixRange(key: ByteArray): IntRange {-    if (nameIdx == null || entryCount == 0 || key.isEmpty()) return IntRange.EMPTY-    val lo = lowerBoundWord(key)-    // Most variants (an accented spelling nobody uses) are empty: one probe settles it+internal fun PoiIndex.Mapped.prefixRange(key: ByteArray, within: IntRange = 0 until entryCount): IntRange {+    if (nameIdx == null || entryCount == 0 || key.isEmpty() || within.isEmpty()) return IntRange.EMPTY+    val end = within.last + 1+    val lo = lowerBoundWord(key, within.first, end)+    // Most spellings (an accented form nobody uses) are empty: one probe settles it     // instead of a second binary search.-    if (lo >= entryCount || !wordStartsWithAt(lo, key)) return IntRange.EMPTY-    val hi = nextPrefix(key)?.let { lowerBoundWord(it) } ?: entryCount+    if (lo >= end || !wordStartsWithAt(lo, key)) return IntRange.EMPTY+    val hi = nextPrefix(key)?.let { lowerBoundWord(it, lo, end) } ?: end     return lo until hi } @@ -57,21 +61,89 @@ internal class QueryToken(val text: String, val ranges: List<IntRange>) {     val size: Int = ranges.sumOf { it.last - it.first + 1 } } -/** The tokens of [query], each with its key variants resolved to ranges. */+/** The tokens of [query], each with its spellings resolved to ranges. */ internal fun PoiIndex.Mapped.queryTokens(query: String): List<QueryToken> =     splitTokens(query.trim()).map { token ->-        val ranges = tokenKeyVariants(token).map { prefixRange(it) }.filterNot { it.isEmpty() }+        val ranges = tokenSpellings(token).flatMap { spellingRanges(it) }.filterNot { it.isEmpty() }         QueryToken(token, disjoint(ranges))     } +/**+ * Ranges of [spelling] and of its one-accent variants ([ACCENTS]): each ASCII letter that+ * commonly carries an accent is tried with those accented forms, one position at a time+ * (the first letter in upper case: only ASCII is case-folded in the index). Most variants+ * exist nowhere and cost one binary search that shares nearly all its pages with the+ * plain spelling's own search; [prefixRange] settles an empty one with a single probe.+ */+private fun PoiIndex.Mapped.spellingRanges(spelling: String): List<IntRange> {+    val out = ArrayList<IntRange>()+    out.add(prefixRange(poiQueryKey(spelling)))+    if (spelling.length < ACCENT_MIN_LEN) return out+    spelling.forEachIndexed { i, c ->+        val forms = if (i == 0) ACCENTS_UPPER[c] else ACCENTS[c]+        forms?.forEach { f ->+            out.add(prefixRange(poiQueryKey(spelling.substring(0, i) + f + spelling.substring(i + 1))))+        }+    }+    return out+}++/** Shortest spelling whose accented forms are looked up (shorter prefixes match broadly already). */+private const val ACCENT_MIN_LEN = 3+ /** [ranges] with duplicates and any range nested inside another dropped, so no entry counts twice. */ private fun disjoint(ranges: List<IntRange>): List<IntRange> {     val unique = ranges.distinct()     return unique.filter { r -> unique.none { o -> o != r && o.first <= r.first && r.last <= o.last } } } -/** Every index sort key the token is looked up under: its ASCII-folded bytes. */-internal fun tokenKeyVariants(token: String): List<ByteArray> = listOf(poiQueryKey(token))+/**+ * Every spelling the token is looked up under (each also with one-accent variants, see+ * [spellingRanges]).+ *+ * The index stores raw UTF-8 with only ASCII case folded, so the spelling a user types and+ * the spelling OSM carries differ in ways the index cannot see:+ *+ *  * possessives — "mcdonalds" vs "McDonald's" (and the typographic ’). Typing the brand+ *    without the apostrophe used to find nothing nearby, because no word starts with+ *    "mcdonalds"; the 139 places that do were all far away;+ *  * apostrophes typed but not in the name — "joe's" vs "Joes";+ *  * diacritics — "cafe" vs "Café", "ecole" vs "École" (an ASCII letter is tried with each+ *    accented form, one position at a time; the first letter in upper case, since only+ *    ASCII is case-folded in the index), and "café" vs "Cafe" (the folded spelling).+ */+internal fun tokenSpellings(token: String): List<String> {+    val lower = token.lowercase()+    val spellings = LinkedHashSet<String>()+    spellings.add(lower)+    val bare = lower.filterNot { it in APOSTROPHES }+    if (bare != lower && bare.isNotEmpty()) spellings.add(bare)+    if (lower.length >= POSSESSIVE_MIN_LEN && lower.endsWith('s') && lower.none { it in APOSTROPHES }) {+        val stem = lower.dropLast(1)+        APOSTROPHES.forEach { spellings.add("$stem${it}s") }+    }+    val folded = PoiSearch.foldDiacritics(lower)+    if (folded != lower && folded.isNotEmpty()) spellings.add(folded)+    return spellings.toList()+}++/** Sort keys of [tokenSpellings], for checking a token against a decoded name. */+internal fun tokenKeyVariants(token: String): List<ByteArray> = tokenSpellings(token).map { poiQueryKey(it) }++/** Apostrophes OSM names use: ASCII and the typographic right single quote. */+private val APOSTROPHES = charArrayOf('\'', '\u2019')++/**+ * The accented lower-case forms tried per ASCII letter: the most frequent ones in planet4's+ * names (é 658 k, ó 341 k, á 327 k, í 315 k, ü 249 k, ä 226 k, ö 194 k, è 144 k, ç 120 k,+ * ñ 87 k), not every Latin-1 form — each costs a lookup on every query.+ */+private val ACCENTS: Map<Char, String> = mapOf(+    'a' to "áä", 'c' to "ç", 'e' to "éè", 'i' to "í", 'n' to "ñ", 'o' to "óö", 'u' to "ü",+)++/** Upper-case accented forms, tried at a word's first letter only (É 84 k, Á 21 k, Ö 20 k). */+private val ACCENTS_UPPER: Map<Char, String> = mapOf('a' to "Á", 'e' to "É", 'o' to "Ö")  /**  * Visit every entry of [token]'s ranges, in index order, as (ordinal, entry index); the
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.ktindex 1fa6e2b240..e43bd0c572 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexWords.kt@@ -108,10 +108,10 @@ internal fun PoiIndex.Mapped.wordStartsWith(range: IntRange, key: ByteArray): Bo     return true } -/** First entry whose word is >= [key], or [entryCount]. */-internal fun PoiIndex.Mapped.lowerBoundWord(key: ByteArray): Int {-    var lo = 0-    var hi = entryCount+/** First entry in `[from, to)` whose word is >= [key], or [to]. */+internal fun PoiIndex.Mapped.lowerBoundWord(key: ByteArray, from: Int = 0, to: Int = entryCount): Int {+    var lo = from+    var hi = to     while (lo < hi) {         val mid = (lo + hi) ushr 1         val w = entryWord(mid)
maps/src/main/java/com/vayunmathur/maps/util/PoiSearch.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiSearch.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiSearch.ktindex 7d31e34674..b394d4891a 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiSearch.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiSearch.kt@@ -14,8 +14,9 @@ import java.text.Normalizer  * that fold exists only to reproduce the Rust writer's sort order for  * binary search. Matching (this file) folds case AND diacritics and drops  * punctuation, so "Café" finds "Cafe" and "joe's" finds "Joes". Candidate- * *lookup* in the word index still uses the writer's fold per token; the- * scan fallback applies this normalisation to the name pool directly.+ * *lookup* in the word index uses the writer's fold per token, looked up under+ * several spellings (tokenKeyVariants: possessives, accents); the ranking+ * re-matches each returned name with this normalisation.  */ object PoiSearch { @@ -29,15 +30,23 @@ object PoiSearch {     const val NO_MATCH = -1      private val MARKS = Regex("\\p{Mn}+")+    private val APOSTROPHES = Regex("['\u2019]")     private val NON_WORD = Regex("[^a-z0-9]+") -    /** Lowercase, strip diacritics, and reduce punctuation to spaces. */+    /**+     * Lowercase, strip diacritics, drop apostrophes, and reduce other punctuation to+     * spaces. Apostrophes are deleted rather than spaced so a possessive stays one word:+     * "McDonald's" and "mcdonalds" normalise alike.+     */     fun normalize(text: String): String {-        val decomposed = Normalizer.normalize(text, Normalizer.Form.NFD)-        val withoutMarks = MARKS.replace(decomposed, "")-        return NON_WORD.replace(withoutMarks.lowercase(), " ").trim()+        val withoutApostrophes = APOSTROPHES.replace(foldDiacritics(text), "")+        return NON_WORD.replace(withoutApostrophes.lowercase(), " ").trim()     } +    /** [text] with combining marks removed ("Café" -> "Cafe"); case and punctuation kept. */+    fun foldDiacritics(text: String): String =+        MARKS.replace(Normalizer.normalize(text, Normalizer.Form.NFD), "")+     /** The normalised word tokens of [text], in order, empties removed. */     fun tokens(text: String): List<String> =         normalize(text).split(' ').filter { it.isNotEmpty() }
maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.ktindex e8be87cef6..756e50ecb7 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.kt@@ -263,6 +263,29 @@ class PoiIndexSmartTest {         assertEquals(listOf("Oakland", "Oakland Grill"), got)     } +    /**+     * The index folds ASCII case only, so a typed spelling and the OSM one used to miss each+     * other: "mcdonalds" found no "McDonald's", "cafe" no "Café", "ecole" no "École".+     */+    @Test+    fun `possessives and accents match either way round`() {+        load(+            listOf(+                Poi(377_749_000, -1_224_194_000, 2, "McDonald's"),+                Poi(377_749_100, -1_224_194_100, 1, "Café Rito"),+                Poi(377_749_200, -1_224_194_200, 11, "École du Louvre"),+                Poi(377_749_300, -1_224_194_300, 1, "Cafe Mason"),+                Poi(377_749_400, -1_224_194_400, 1, "Joes Diner"),+            )+        )+        fun names(q: String) = PoiIndex.searchByName(q, 37.7749, -122.4194).map { it.name }.toSet()+        assertEquals(setOf("McDonald's"), names("mcdonalds"))+        assertEquals(setOf("Café Rito", "Cafe Mason"), names("cafe"))+        assertEquals(setOf("Café Rito", "Cafe Mason"), names("café"))+        assertEquals(setOf("École du Louvre"), names("ecole"))+        assertEquals(setOf("Joes Diner"), names("joe's"))+    }+     @Test     fun `buildSearchBoost favors saved places over recents`() {         val boost = buildSearchBoost(