Modern Apps git

← Modern-Apps.git

maps: rank search by text match and distance together (#mapsearch)

Commit
422ffc40ecc127e31351b1f458fa27c6b0534cae
Author
Vayun Mathur <[email protected]>
When
2026-11-13 20:24 UTC (22 days ago)
Parents
801e028
Symptom (owner): "it constantly finds places super far away instead of
right here."

Root cause: the indexed search sorted by text-match bucket first, then
"the name IS the query and it is a place label (or within 55 km)",
then boost, and only then distance. Any exact place label anywhere on
earth therefore led the list. Measured from Union Square, SF, on the
planet archive (before -> after, top results):

  museum   Museum (village) 16,987 km, Museum 24,080 km x3, ...
           -> Museum of the African Diaspora 0.55 km, California
              Historical Society Museum 0.54 km, SFMOMA 0.65 km, ...
  coffee   Coffee (hamlet) 370 km, Coffee 3,737 km, Coffee 3,800 km
           -> Coffee Bar 0.53 km, Coffee Bar 0.54 km, ...
  pi       Pi (place) 10,590 km first -> Pinecrest Diner 0.24 km, ...
  golden gate  "Golden Gate" place labels 2,971-25,108 km in rows 3-9
           -> Golden Gate Fortune Cookie Factory, Tap Room, Hotel,
              Theater ... all within 1 km
  oakland  Oakland 12 km then nine other Oaklands 631-2,344 km away
           -> Oakland 12 km, then Oakland's own stations/landmarks

Change (rankCandidates): one blended score per row,
  tier penalty (exact 0, name-prefix 1, every-word 2, substring 3.5,
  typo 4.5) + log2(1 + km / 1 km)
  - 3 if it is a place label whose name is exactly the query
  - 1 for landmarks people search across a city for (park,
    attraction, museum, station, place label)
  - min(log2(1 + boost), 2.9) for recents/saved places.
Within walking distance the text decides; beyond it each doubling of
distance costs as much as a weaker match. A city is still found by its
name (8x distance credit), it just no longer beats everything nearer.
The boost cap keeps an exact match ahead of a familiar typo (the
PoiIndexSmartTest contract) while letting a saved place beat a
same-tier match several times nearer.

The grid join now always covers the 1.5 km and 8 km boxes before it
may stop, so a landmark a few km out competes with the shops named
after it ("golden gate bridge" -> the bridge, 7.3 km, first).
Shortlisting uses each candidate's best reachable score so decoding
only 30 names never drops a row that would rank. The scan fallback
(no word index) keeps its old ordering.

Tests: PoiIndexSmartTest gains three cases (a far exact place label
does not outrank a nearby match; a nearby word match beats a phrase
match on another continent; a nearby exact place label leads the shops
named after it). PoiIndexTest/PoiIndexSmartTest/PoiArchiveTest and the
real-archive PoiArchiveRealFileTest pass standalone; container build
runs the module suite.

Diff

maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.ktindex 3b3048f821..3543c245ec 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt@@ -52,10 +52,10 @@ data class SearchResult( )  /**- * Weight a saved (starred) place carries in search ranking: large enough that- * a favorite always outranks an equally-matching unvisited place (boost only- * breaks ties within a text-match rank, so an exact match still beats a- * familiar typo), but still only a reorder — [PoiIndex.searchByName] never+ * Weight a saved (starred) place carries in search ranking: the indexed search turns a+ * weight into distance credit capped just below a text-tier step from a typo, so a+ * favorite outranks an equally-matching place several times nearer while an exact match+ * still beats a familiar typo. Still only a reorder — [PoiIndex.searchByName] never  * returns a non-match.  */ internal const val SAVED_SEARCH_BOOST = 1_000_000.0
maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.ktindex 8ddbf7ff17..af6286d9d2 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiCategories.kt@@ -205,8 +205,8 @@ object PoiCategories {     private const val TYPE_HOTEL = 8     private const val TYPE_BANK = 9     private const val TYPE_SCHOOL = 11-    private const val TYPE_PARK = 12-    private const val TYPE_ATTRACTION = 15+    internal const val TYPE_PARK = 12+    internal const val TYPE_ATTRACTION = 15     private const val TYPE_THEATRE = 18     private const val TYPE_LIBRARY = 19     private const val TYPE_POST_OFFICE = 20@@ -217,7 +217,7 @@ object PoiCategories {     private const val TYPE_BOOKS = 30     private const val TYPE_SPORTS = 32     private const val TYPE_VETERINARY = 36-    private const val TYPE_MUSEUM = 38+    internal const val TYPE_MUSEUM = 38      /**      * The station type, whose taps open a departure board rather than a place sheet.
maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.ktindex 744ff7e6c7..bef99762c5 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt@@ -645,10 +645,12 @@ object PoiIndex {      * indexed path matches a prefix *of any word*. That is a deliberate narrowing —      * mid-word matches are lost, whole-word ones are not.      *-     * Ranking, same on both paths: every query token must match (multi-word+     * Matching, same on both paths: every query token must match (multi-word      * queries matched nothing before); tokens within one edit of a word match-     * too, ranked below exact ones; [boost] (recents + saved places) only-     * breaks ties within a rank — it never resurrects a non-match.+     * too, ranked below exact ones. The indexed path ranks by one blended score+     * of text match and log distance (place labels, landmarks and [boost] —+     * recents + saved places — earn distance credit); the scan fallback keeps+     * rank-then-distance. [boost] never resurrects a non-match.      *      * [cancelled] is polled between phases: a caller whose result is no longer wanted (the      * user typed another character) gets an empty list back early instead of the lookup
maps/src/main/java/com/vayunmathur/maps/util/PoiSearchEngine.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiSearchEngine.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiSearchEngine.ktindex a98df7fde5..97105db75e 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiSearchEngine.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiSearchEngine.kt@@ -25,7 +25,8 @@ package com.vayunmathur.maps.util  *  4. **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.+ *  5. **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.  */@@ -41,7 +42,14 @@ private const val MATERIALIZE_CAP = 250_000 private const val GLOBAL_ALL_CAP = 1_500  /** Half-sizes of the boxes around the bias point the grid join grows through. */-private val RING_HALF_KM = doubleArrayOf(1.5, 6.0, 25.0)+private val RING_HALF_KM = doubleArrayOf(1.5, 8.0, 25.0)++/**+ * Boxes always joined, even when the first already filled the page: a city's landmark a+ * few km out ("golden gate" -> the bridge, 6.5 km from Union Square) must get to compete+ * with the dozen "Golden Gate …" shops next door. The join is a sequential grid read.+ */+private const val MIN_RINGS = 2  /** Survivors nearest the bias point in file order read when the boxes come up short. */ private const val REGIONAL_WINDOW = 1_500@@ -53,10 +61,6 @@ private const val NAME_SCAN_BUDGET = 5_000 /** Candidates whose names are decoded for the final ranking. */ private const val SHORTLIST = 30 -/** Place-label candidates decoded besides the shortlist (a city's exact name is wanted- *  from anywhere). */-private const val PLACE_SHORTLIST = 20- /** Shortest token allowed to drive the candidate scan. */ private const val MIN_DRIVER_LEN = 2 @@ -162,13 +166,13 @@ internal class CandidateSearch(         // Near first: the grid's ordinals are a sequential read, a survivor's coordinates a         // random one, so even a small survivor set is only placed whole when the boxes         // around the bias point did not already fill the page.-        for (half in RING_HALF_KM) {+        RING_HALF_KM.forEachIndexed { ring, half ->             forEachOrdinalNear(half) { o ->                 val i = table.indexOf(o)                 if (i >= 0 && survivors[i]) addIndexed(o, table, i)                 true             }-            if (found.size >= bias.limit || cancelled()) return+            if ((ring + 1 >= MIN_RINGS && found.size >= bias.limit) || cancelled()) return         }         if (count <= GLOBAL_ALL_CAP) {             for (i in 0 until table.size) if (survivors[i]) addIndexed(table.ordinals[i], table, i)@@ -318,29 +322,80 @@ private fun lowerBoundPacked(packed: LongArray, ordinal: Int): Int {     return lo } -private class RankedRow(-    val record: PoiIndex.PoiRecord,-    val rank: Int,-    val exact: Boolean,-    val boost: Double,-    val distKm: Double,+/**+ * Text-match penalty per [PoiSearch] tier, in the same units as [distancePenalty] (one unit+ * = doubling the distance past [DIST_SCALE_KM]). A step between tiers is worth roughly a+ * 2-3x difference in distance: a "Pizza Hut" a few hundred metres away still beats a+ * "Joe's Pizza" next door, but not one across town.+ */+private fun tierPenalty(tier: Int): Double = when (tier) {+    PoiSearch.TIER_EXACT -> 0.0+    PoiSearch.TIER_PREFIX -> PENALTY_PREFIX+    PoiSearch.TIER_TOKENS -> PENALTY_TOKENS+    PoiSearch.TIER_SUBSTRING, PoiSearch.TIER_CATEGORY -> PENALTY_SUBSTRING+    else -> PENALTY_FUZZY+}++private const val PENALTY_PREFIX = 1.0+private const val PENALTY_TOKENS = 2.0+private const val PENALTY_SUBSTRING = 3.5+private const val PENALTY_FUZZY = 4.5++/** Distance below which places count as equally near (walking distance), in km. */+private const val DIST_SCALE_KM = 1.0++/**+ * A place label whose name IS the query (a city, a neighbourhood) is searched for from+ * afar, and its point stands for a whole area: it gets this much distance credit (~8x).+ * It used to be a tier of its own above every distance, so from San Francisco "museum"+ * opened on a village called Museum 16,987 km away and "coffee" on a hamlet 370 km away.+ */+private const val PLACE_EXACT_BONUS = 3.0++/**+ * The most a recency/favorites weight can buy: just under a tier step from a typo, so a+ * familiar typo never outranks an exact match, while a saved place still wins over a+ * same-tier match several times nearer.+ */+private const val MAX_BOOST_BONUS = 2.9++/**+ * Distance credit for kinds people search for by name from across a city — landmarks,+ * parks, museums, stations, place labels — over the shops that borrow their names.+ */+private const val NOTABLE_BONUS = 1.0++private val NOTABLE_TYPES = setOf(+    PoiCategories.TYPE_PARK, PoiCategories.TYPE_ATTRACTION, PoiCategories.TYPE_MUSEUM,+    PoiCategories.STATION_TYPE, PoiCategories.TYPE_PLACE, ) -/** "Local" for the exact-name tier: ~0.5° (≈55 km) from the centre. */-private const val EXACT_LOCAL_KM = 55.0+private fun typeBonus(type: Int): Double = if (type in NOTABLE_TYPES) NOTABLE_BONUS else 0.0 -/** The pre-planet rank buckets: phrase, every word (or a substring), typo. */-private fun rankOf(tier: Int): Int = when (tier) {-    PoiSearch.TIER_EXACT, PoiSearch.TIER_PREFIX -> 0-    PoiSearch.TIER_TOKENS, PoiSearch.TIER_SUBSTRING, PoiSearch.TIER_CATEGORY -> 1-    else -> 2-}+private fun distancePenalty(km: Double): Double = log2(1.0 + km / DIST_SCALE_KM)++private fun boostBonus(weight: Double): Double =+    if (weight <= 0.0) 0.0 else minOf(log2(1.0 + weight), MAX_BOOST_BONUS)++private fun log2(x: Double): Double = Math.log(x) / LN2++private val LN2 = Math.log(2.0)++private class RankedRow(val record: PoiIndex.PoiRecord, val score: Double, val distKm: Double)  /**- * Rank, then decode only the rows that can be returned: the [SHORTLIST] best by (rank,- * distance) plus the nearest phrase-matching place labels. Within a rank a name that IS- * the query comes first when it is a place label or local, then the user's signal, then- * distance.+ * Rank by one blended score — text-match penalty + log distance - place/notable/boost credit — and+ * decode only the rows that can be returned.+ *+ * Distance used to be a tie-break: rank buckets first, then "is it exactly the name", and+ * only then distance, so any exact or phrase match anywhere on earth beat a word match+ * across the street ("it constantly finds places super far away instead of right here").+ * Now distance is part of the score, logarithmically: within walking distance the text+ * decides, beyond it each doubling of distance costs as much as a weaker match.+ *+ * Shortlisting uses the most optimistic score a candidate could reach once its name is+ * read (a phrase match may turn out to be the exact name, a place label may earn the place+ * credit), so the decode cannot drop a row that would have ranked.  */ internal fun rankCandidates(     m: PoiIndex.Mapped,@@ -348,17 +403,25 @@ internal fun rankCandidates(     candidates: Collection<Candidate>,     bias: SearchBias, ): List<PoiIndex.PoiRecord> {-    val byRank = candidates.sortedWith(compareBy<Candidate> { rankOf(it.tier) }.thenBy { it.distKm })-    val places = byRank.filter { it.type == PoiCategories.TYPE_PLACE && rankOf(it.tier) == 0 }.take(PLACE_SHORTLIST)-    val shortlist = (byRank.take(SHORTLIST) + places).distinctBy { it.ordinal }-    val whole = query.trim()-    val out = shortlist.map { c ->+    val queryNorm = PoiSearch.normalize(query)+    val queryWords = PoiSearch.tokens(query)+    val shortlist = candidates.sortedBy { optimisticScore(it) }.take(SHORTLIST)+    return shortlist.map { c ->         val record = m.record(c.ordinal)-        val exact = record.name.equals(whole, ignoreCase = true) &&-            (record.type == PoiCategories.TYPE_PLACE || c.distKm <= EXACT_LOCAL_KM)-        RankedRow(record, rankOf(c.tier), exact, boostWeight(bias.boost, record.name), c.distKm)-    }-    return out.sortedWith(-        compareBy<RankedRow> { it.rank }.thenBy { !it.exact }.thenByDescending { it.boost }.thenBy { it.distKm },-    ).take(bias.limit).map { it.record }+        val tier = PoiSearch.matchTier(record.name, queryNorm, queryWords)+            .takeIf { it != PoiSearch.NO_MATCH } ?: c.tier+        val place = if (tier == PoiSearch.TIER_EXACT && record.type == PoiCategories.TYPE_PLACE) PLACE_EXACT_BONUS else 0.0+        val score = tierPenalty(tier) + distancePenalty(c.distKm) - place - typeBonus(record.type) -+            boostBonus(boostWeight(bias.boost, record.name))+        RankedRow(record, score, c.distKm)+    }.sortedWith(compareBy<RankedRow> { it.score }.thenBy { it.distKm })+        .take(bias.limit)+        .map { it.record }+}++/** The best score [c] can reach once its name is known (see [rankCandidates]). */+private fun optimisticScore(c: Candidate): Double {+    val tier = if (c.tier == PoiSearch.TIER_PREFIX) PoiSearch.TIER_EXACT else c.tier+    val place = if (c.tier == PoiSearch.TIER_PREFIX && c.type == PoiCategories.TYPE_PLACE) PLACE_EXACT_BONUS else 0.0+    return tierPenalty(tier) + distancePenalty(c.distKm) - place - typeBonus(c.type) }
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 eb9ccad75a..e8be87cef6 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexSmartTest.kt@@ -220,6 +220,49 @@ class PoiIndexSmartTest {         assertEquals(listOf("Pizza Hut", "Piza Kitchen"), got)     } +    /**+     * The "places super far away" bug: an exact-name place label used to be a tier above every+     * distance, so from San Francisco "museum" opened on a village called Museum on the other+     * side of the world.+     */+    @Test+    fun `a far exact place label does not outrank a nearby match`() {+        load(+            listOf(+                Poi(377_749_000, -1_224_194_000, 38, "Museum of Modern Art"),+                Poi(-338_688_000, 1_512_093_000, PoiCategories.TYPE_PLACE, "Museum"),+            )+        )+        val got = PoiIndex.searchByName("museum", 37.7749, -122.4194).map { it.name }+        assertEquals(listOf("Museum of Modern Art", "Museum"), got)+    }++    /** Distance is part of the score, not a tie-break under the text tier. */+    @Test+    fun `a nearby word match outranks a phrase match on another continent`() {+        load(+            listOf(+                Poi(515_074_000, -1_278_000, 1, "Pizza Palace"),+                Poi(377_749_000, -1_224_194_000, 2, "Joe's Pizza"),+            )+        )+        val got = PoiIndex.searchByName("pizza", 37.7749, -122.4194).map { it.name }+        assertEquals(listOf("Joe's Pizza", "Pizza Palace"), got)+    }++    /** A city searched for by name from nearby still opens on the city. */+    @Test+    fun `a nearby exact place label leads the shops named after it`() {+        load(+            listOf(+                Poi(378_044_557, -1_222_713_560, PoiCategories.TYPE_PLACE, "Oakland"),+                Poi(377_960_000, -1_222_750_000, 4, "Oakland Grill"),+            )+        )+        val got = PoiIndex.searchByName("oakland", 37.7879, -122.4075).map { it.name }+        assertEquals(listOf("Oakland", "Oakland Grill"), got)+    }+     @Test     fun `buildSearchBoost favors saved places over recents`() {         val boost = buildSearchBoost(