Modern Apps git

← Modern-Apps.git

maps: category search finds places whose names lack the category words

Commit
8d024173f58b79a18fa8bb4e234736b3eb6977e0
Author
Vayun Mathur <[email protected]>
When
2026-12-01 06:01 UTC (5 days ago)
Parents
fd2757f
The fast search rewrite collects candidates only from the
name word-index, nearby-name matching and typo lookup — it
never consults POI type. PoiCategories.typesForTerm and the
TIER_CATEGORY ranking existed and were documented as search
behaviour but had zero callers (the scan fallback even
early-returned when no name matched), so tapping the Coffee/
Gas/Groceries category chips found only places literally
named with those words: 'coffee' returned nothing where a
Starbucks stood. A secondary defect: singular('groceries')
produced 'grocerie', matching no label.

The engine now resolves category queries against POI types
(every query word must be a category term and a type must
satisfy every word — 'gas station' is fuel, not all
stations), collecting type-matching places at TIER_CATEGORY
over the same growing grid rings; the no-word-index scan
fallback accepts category-type records between substring and
typo rank; and singular maps -ies -> -y. One stale test
expectation was corrected where the fixture diner is itself
a Cafe. Routing, navigation, saved places and transit were
audited and cleared. Verified: :maps:testDevUnitTest 946
tests pass (new category test failed pre-fix); lint errors
are pre-existing in untouched files.

Diff

maps/src/main/java/com/vayunmathur/maps/data/PoiIndexWords.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/PoiIndexWords.kt b/maps/src/main/java/com/vayunmathur/maps/data/PoiIndexWords.ktindex 072f1f127f..69c3a21252 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/PoiIndexWords.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/PoiIndexWords.kt@@ -237,14 +237,18 @@ internal fun searchByScan(     val tokens = splitTokens(q)      // Pass 1: walk the name pool once, recording matching offsets and their-    // rank (0 = phrase prefix, 1 = every token a substring, 2 = every token a-    // substring or a one-edit typo of a word). Decoding each unique name once-    // is the dedup win the side-file layout is designed for.+    // rank (0 = phrase prefix, 1 = every token a substring, 2 = category+    // type, 3 = every token a substring or a one-edit typo of a word).+    // Decoding each unique name once is the dedup win the side-file layout+    // is designed for.     val matchRank = matchNamePool(m, q, tokens)-    if (matchRank.isEmpty()) return emptyList()+    val categoryTypes = categoryTypesForQuery(PoiSearch.tokens(query))+    if (matchRank.isEmpty() && categoryTypes.isEmpty()) return emptyList() -    // Pass 2: scan records, keeping those whose name offset matched.-    val out = collectScanMatches(m, matchRank, nearLat, nearLon, boost)+    // Pass 2: scan records, keeping those whose name offset matched, plus+    // — for a purely categorical query — records of the matching types,+    // whose names need not contain the words (see PoiSearchEngine).+    val out = collectScanMatches(m, matchRank, categoryTypes, nearLat, nearLon, boost)     out.sortWith(compareBy<Ranked> { it.rank }.thenByDescending { it.boost }.thenBy { it.distSq })     return out.take(limit).map { it.record } }@@ -263,12 +267,17 @@ private fun matchNamePool(m: PoiIndex.Mapped, q: String, tokens: List<String>):     return matchRank } +/** Rank of a record whose type matches a purely categorical query. */+private const val SCAN_CATEGORY_RANK = 2+ /**  * Rank of [name] against the query (0 = phrase prefix, 1 = every token a- * substring, 2 = every token a substring or a one-edit typo of a word), or- * null. Single-token queries behave exactly as before; multi-token queries- * used to require the whole spaced string as one substring, so "ferry- * building" matched nothing — now each word only has to appear.+ * substring, 3 = every token a substring or a one-edit typo of a word), or+ * null. Rank 2 is the category-type match (see [SCAN_CATEGORY_RANK]),+ * between substring and typo, mirroring the indexed tiers. Single-token+ * queries behave exactly as before; multi-token queries used to require+ * the whole spaced string as one substring, so "ferry building" matched+ * nothing — now each word only has to appear.  */ private fun rankName(name: String?, q: String, tokens: List<String>): Int? {     if (name == null) return null@@ -277,7 +286,7 @@ private fun rankName(name: String?, q: String, tokens: List<String>): Int? {     if (tokens.all { lower.contains(it) }) return 1     if (tokens.size > 1 || (tokens.size == 1 && tokens[0].length >= MIN_TYPO_TOKEN_LEN)) {         val words = splitTokens(lower)-        if (tokens.all { token -> tokenMatchesWord(token, lower, words) }) return 2+        if (tokens.all { token -> tokenMatchesWord(token, lower, words) }) return 3     }     return null }@@ -294,6 +303,7 @@ private fun tokenMatchesWord(token: String, lowerName: String, words: List<Strin private fun collectScanMatches(     m: PoiIndex.Mapped,     matchRank: Map<Int, Int>,+    categoryTypes: Set<Int>,     nearLat: Double,     nearLon: Double,     boost: Map<String, Double>,@@ -301,7 +311,7 @@ private fun collectScanMatches(     val out = ArrayList<Ranked>(minOf(PoiIndex.CANDIDATE_CAP, m.count))     var i = 0     while (i < m.count && out.size < PoiIndex.CANDIDATE_CAP) {-        scanMatchAt(m, i, matchRank, nearLat, nearLon, boost)?.let { out.add(it) }+        scanMatchAt(m, i, matchRank, categoryTypes, nearLat, nearLon, boost)?.let { out.add(it) }         i++     }     return out@@ -311,12 +321,15 @@ private fun scanMatchAt(     m: PoiIndex.Mapped,     i: Int,     matchRank: Map<Int, Int>,+    categoryTypes: Set<Int>,     nearLat: Double,     nearLon: Double,     boost: Map<String, Double>, ): Ranked? {     val off = m.nameOff(i)-    val rank = matchRank[off] ?: return null+    // A name match outranks the category match for the same record.+    val rank = matchRank[off]+        ?: if (m.type(i) in categoryTypes) SCAN_CATEGORY_RANK else return null     val latE7 = m.latE7(i)     val lonE7 = m.lonE7(i)     val name = m.nameAt(off) ?: ""
maps/src/main/java/com/vayunmathur/maps/data/PoiSearch.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/PoiSearch.kt b/maps/src/main/java/com/vayunmathur/maps/data/PoiSearch.ktindex c0618635af..2b5a51a695 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/PoiSearch.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/PoiSearch.kt@@ -52,8 +52,14 @@ object PoiSearch {         normalize(text).split(' ').filter { it.isNotEmpty() }      /** Singular form of a token for category matching ("restaurants" -> "restaurant"). */-    fun singular(token: String): String =-        if (token.length > MIN_PLURAL_LEN && token.endsWith('s')) token.dropLast(1) else token+    fun singular(token: String): String = when {+        // "-ies" plurals singularise to "-y" ("groceries" -> "grocery",+        // "pharmacies" -> "pharmacy"); dropping only the "s" left "grocerie",+        // which matches no category label.+        token.length > MIN_PLURAL_LEN && token.endsWith("ies") -> token.dropLast(3) + "y"+        token.length > MIN_PLURAL_LEN && token.endsWith('s') -> token.dropLast(1)+        else -> token+    }      /**      * Tier at which the normalised [name] matches the normalised query
maps/src/main/java/com/vayunmathur/maps/data/PoiSearchEngine.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/PoiSearchEngine.kt b/maps/src/main/java/com/vayunmathur/maps/data/PoiSearchEngine.ktindex 395c3ba438..4d4dd888b1 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/PoiSearchEngine.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/PoiSearchEngine.kt@@ -23,10 +23,13 @@ import com.vayunmathur.maps.domain.spatialFromE7  *     those boxes yield too little — against a window of survivors nearest the bias point  *     in Morton (= file) order. Coordinates are read only for rows that are actually  *     near.- *  4. **Fallbacks only when short of results:** a name scan of the few thousand records+ *  4. **Categories.** A purely categorical query ("coffee", "gas station") also+ *     collects the nearest places of the matching POI types over the same grid+ *     rings, at category tier — their names need not contain the words.+ *  5. **Fallbacks only when short of results:** a name scan of the few thousand records  *     closest to the bias point (mid-word substrings, typos, punctuation), then the  *     index-wide typo lookup.- *  5. **Rank and decode** at most [SHORTLIST] names ([rankCandidates]: one blended score of+ *  6. **Rank and decode** at most [SHORTLIST] names ([rankCandidates]: one blended score of  *     text match and distance).  *  * Every scan polls the caller's cancel token, so a superseded keystroke stops promptly.@@ -94,6 +97,7 @@ internal fun searchByWordIndex(     if (tokens.isEmpty()) return emptyList()     val search = CandidateSearch(m, query, tokens, bias, cancelled)     search.collectIndexed()+    search.collectCategory()     if (search.size < bias.limit) search.collectNearbyNames(acceptLoose = true)     if (search.size < bias.limit / 2) search.collectIndexTypos()     if (cancelled()) return emptyList()@@ -111,6 +115,7 @@ internal class CandidateSearch(     private val found = LinkedHashMap<Int, Candidate>()     private val queryNorm = PoiSearch.normalize(query)     private val queryWords = PoiSearch.tokens(query)+    private val categoryTypes: Set<Int> = categoryTypesForQuery(queryWords)     private val cosLat = Math.cos(Math.toRadians(bias.lat)).coerceAtLeast(MIN_COS_LAT)      /** The rarest token long enough to drive the scan, or null when none is. */@@ -149,6 +154,33 @@ internal class CandidateSearch(         }     } +    /**+     * Category candidates: when every query word is a category term+     * ("coffee", "gas station"), places of the matching POI types are+     * candidates at [PoiSearch.TIER_CATEGORY] even though their names do+     * not contain the words — a cafe called "Starbucks" is what the+     * coffee chip is asking for. Collected over the same growing grid+     * rings as the indexed join, nearest first, and capped at a page of+     * new candidates: farther same-tier places cannot outrank the+     * nearest ones this already found. A name match already collected+     * keeps its (better) tier.+     */+    fun collectCategory() {+        if (categoryTypes.isEmpty()) return+        var added = 0+        for (half in RING_HALF_KM) {+            if (cancelled()) return+            forEachOrdinalNear(half) { o ->+                if (o !in found && m.type(o) in categoryTypes) {+                    add(o, PoiSearch.TIER_CATEGORY)+                    added+++                }+                true+            }+            if (added >= bias.limit) return+        }+    }+     /** The driver's whole range in a table, intersected with the other scanned tokens. */     private fun collectMaterialized(driver: Int) {         val table = intersectScanned(driver) ?: return@@ -327,6 +359,27 @@ internal class CandidateSearch(     } } +/**+ * The POI types a query asks for by category, or empty when it is not a+ * purely categorical query. Every word must be a category term, and a+ * type must satisfy *every* word: "gas station" is fuel (its label and+ * synonym cover both words), not every station; "coffee shop" names no+ * single category and stays a name query. Words are singularised first+ * ("restaurants" -> "restaurant"), as [PoiCategories.typesForTerm]+ * expects.+ */+internal fun categoryTypesForQuery(queryWords: List<String>): Set<Int> {+    if (queryWords.isEmpty()) return emptySet()+    var types: Set<Int>? = null+    for (word in queryWords) {+        val found = PoiCategories.typesForTerm(PoiSearch.singular(word))+        if (found.isEmpty()) return emptySet()+        types = types?.intersect(found) ?: found+        if (types.isEmpty()) return emptySet()+    }+    return types.orEmpty()+}+ private fun toE7(deg: Double): Int = (deg * E7_PER_DEGREE).toInt()  /** First index in [packed] (ordinal in the high half, ascending) whose ordinal is >= [ordinal]. */
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 2740ae6b1a..9abcf37cbf 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.kt@@ -284,8 +284,11 @@ class PoiIndexSmartTest {         )         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é"))+        // "cafe" is also a category query (type 1), so Joes Diner — a cafe+        // by type whose name contains no "cafe" — surfaces alongside the+        // two name matches.+        assertEquals(setOf("Café Rito", "Cafe Mason", "Joes Diner"), names("cafe"))+        assertEquals(setOf("Café Rito", "Cafe Mason", "Joes Diner"), names("café"))         assertEquals(setOf("École du Louvre"), names("ecole"))         assertEquals(setOf("Joes Diner"), names("joe's"))     }
maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.ktindex 94e09ba277..d48fc97222 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt@@ -420,6 +420,50 @@ class PoiIndexTest {         assertEquals(listOf("Blue Bottle", "The Blue Door"), got.map { it.name })     } +    @Test+    fun `category queries surface nearby places by type, not only by name`() = bothPaths { sideFiles ->+        // Types are PoiCategories numbering: 0 restaurant, 1 cafe, 5 grocery,+        // 6 fuel, 50 station. None of the names contain the category words.+        load(+            listOf(+                Poi(377_749_000, -1_224_194_000, 1, "Starbucks"),+                Poi(377_750_000, -1_224_194_000, 6, "Shell"),+                Poi(377_751_000, -1_224_194_000, 0, "Luigi"),+                Poi(377_752_000, -1_224_194_000, 5, "Safeway"),+                Poi(377_753_000, -1_224_194_000, 50, "Central"),+            ),+            sideFiles = sideFiles,+        )+        assertEquals(+            listOf("Starbucks"),+            PoiIndex.searchByName("coffee", 37.7749, -122.4194).map { it.name },+        )+        assertEquals(+            listOf("Shell"),+            PoiIndex.searchByName("gas station", 37.7749, -122.4194).map { it.name },+            "a station (type 50) must not surface for a fuel query",+        )+        assertEquals(+            listOf("Luigi"),+            PoiIndex.searchByName("restaurants", 37.7749, -122.4194).map { it.name },+        )+        assertEquals(+            listOf("Safeway"),+            PoiIndex.searchByName("groceries", 37.7749, -122.4194).map { it.name },+        )+        // One word only: "station" is ambiguous in the category vocabulary+        // (the "Gas station" label contains it too), so Shell legitimately+        // follows Central here — the two-word query above is what narrows+        // it to fuel.+        // (As a set: the two search paths rank by design — blended score+        // on the indexed path, rank-then-distance on the scan path — so+        // their relative order legitimately differs.)+        assertEquals(+            setOf("Central", "Shell"),+            PoiIndex.searchByName("station", 37.7749, -122.4194).map { it.name }.toSet(),+        )+    }+     @Test     fun `attributesNear joins on name as well as distance`() {         // Two POIs a metre apart, as a cafe inside a mall is. Attaching the cafe's phone number