fix(search): order numbered headwords naturally

Deduplicate matches in the searcher and apply one ordering pass after
merging dictionaries: display length first, then natural numeric-aware
order. Keep numbered series with the same prefix and suffix contiguous
within each dictionary and place numerals before non-numeric characters.
This commit is contained in:
OneWay committed 2026-10-15 13:06:05 +08:00
1 parent e20af9c1ff
commit f92d0588bd
5 files changed
+88 -47

No files matched your search

@@ -43,6 +43,16 @@ private fun bigUnitOf(c: Char): Long = when (c) {
private fun isNumeralChar(c: Char): Boolean = private fun isNumeralChar(c: Char): Boolean =
digitOf(c) >= 0 || smallUnitOf(c) > 0L || fixedTensOf(c) > 0L || bigUnitOf(c) > 0L digitOf(c) >= 0 || smallUnitOf(c) > 0L || fixedTensOf(c) > 0L || bigUnitOf(c) > 0L
internal fun naturalNumberRange(value: String): IntRange? {
var start = 0
while (start < value.length && !isNumeralChar(value[start])) start++
if (start == value.length) return null
var end = start + 1
while (end < value.length && isNumeralChar(value[end])) end++
return start until end
}
private fun satMul(a: Long, b: Long): Long = private fun satMul(a: Long, b: Long): Long =
if (a != 0L && b > NUMERAL_CAP / a) NUMERAL_CAP else minOf(a * b, NUMERAL_CAP) if (a != 0L && b > NUMERAL_CAP / a) NUMERAL_CAP else minOf(a * b, NUMERAL_CAP)
@@ -118,7 +128,12 @@ private fun compareNatural(a: String, b: String): Int {
j = endB j = endB
} }
else -> { else -> {
if (ca != cb) return ca.compareTo(cb) if (ca != cb) {
val numeralA = !asciiA && isNumeralChar(ca)
val numeralB = !asciiB && isNumeralChar(cb)
if (numeralA != numeralB) return if (numeralA) -1 else 1
return ca.compareTo(cb)
}
i++ i++
j++ j++
} }
@@ -5,10 +5,9 @@ import androidx.paging.PagingState
import com.example.research.core.domain.model.Dictionary import com.example.research.core.domain.model.Dictionary
import com.example.research.core.domain.model.IndexEntry import com.example.research.core.domain.model.IndexEntry
import com.example.research.core.performance.ReSearchTrace import com.example.research.core.performance.ReSearchTrace
import com.example.research.core.util.sanitizeQuery
import com.example.research.data.parser.IndexSearcher import com.example.research.data.parser.IndexSearcher
import com.example.research.data.parser.SearchRankingContext import com.example.research.data.parser.sortByCharCountThenNatural
import com.example.research.data.parser.rankBySearchRelevance
import kotlinx.coroutines.async import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
@@ -68,9 +67,8 @@ class IndexEntryPagingSource(
} }
} }
val normalizedQuery = query.sanitizeQuery().lowercase().trim()
val ranked = rawResults val ranked = rawResults
.rankBySearchRelevance(SearchRankingContext(normalizedQuery)) .sortByCharCountThenNatural()
.distinctBy { Triple(it.dictionaryPath, it.word, it.offset.value) } .distinctBy { Triple(it.dictionaryPath, it.word, it.offset.value) }
LoadResult.Page( LoadResult.Page(
@@ -122,9 +122,7 @@ class IndexSearcher(private val context: Context) {
} }
} }
} }
(prefixMatches + substringMatches) (prefixMatches + substringMatches).distinctBy { it.articleKey() }
.rankBySearchRelevance(SearchRankingContext(normalizedQuery, foldedQuery))
.distinctBy { it.articleKey() }
} }
resultsCache.put(cacheKey, results) resultsCache.put(cacheKey, results)
results results
@@ -2,50 +2,82 @@ package com.example.research.data.parser
import com.example.research.core.domain.model.IndexEntry import com.example.research.core.domain.model.IndexEntry
import com.example.research.core.util.NaturalStringComparator import com.example.research.core.util.NaturalStringComparator
import com.example.research.core.util.foldLatinDiacritics import com.example.research.core.util.naturalNumberRange
internal data class SearchRankingContext( private data class NumberedSeriesKey(
val normalizedQuery: String, val dictionaryPath: String,
val foldedQuery: String = normalizedQuery.foldLatinDiacritics(), val prefix: String,
val suffix: String,
) )
private data class SortKey( internal fun List<IndexEntry>.sortByCharCountThenNatural(): List<IndexEntry> {
val matchTier: Int,
val exactMatch: Int,
val charCount: Int,
val word: String,
val entry: IndexEntry,
)
internal fun List<IndexEntry>.rankBySearchRelevance(
ranking: SearchRankingContext
): List<IndexEntry> {
if (size < 2) return this if (size < 2) return this
return map { entry -> val charCounts = IntArray(size)
val word = entry.word var minCount = Int.MAX_VALUE
var maxCount = Int.MIN_VALUE
for (i in indices) {
val entry = this[i]
val displayKey = entry.originalWord val displayKey = entry.originalWord
.trim() .trim()
.ifEmpty { entry.word.trim() } .ifEmpty { entry.word.trim() }
val count = displayKey.codePointCount(0, displayKey.length)
charCounts[i] = count
if (count < minCount) minCount = count
if (count > maxCount) maxCount = count
}
SortKey( val buckets = arrayOfNulls<ArrayList<IndexEntry>>(maxCount - minCount + 1)
matchTier = when { for (i in indices) {
!entry.isAlias && word.startsWith(ranking.normalizedQuery) -> 0 val bucketIndex = charCounts[i] - minCount
entry.isAlias && word.startsWith(ranking.foldedQuery) -> 1 (buckets[bucketIndex] ?: ArrayList<IndexEntry>().also { buckets[bucketIndex] = it })
!entry.isAlias && word.foldLatinDiacritics().startsWith(ranking.foldedQuery) -> 1 .add(this[i])
else -> 2
},
exactMatch = if (word == ranking.normalizedQuery) 0 else 1,
charCount = displayKey.codePointCount(0, displayKey.length),
word = word,
entry = entry,
)
} }
.sortedWith(
compareBy<SortKey> { it.matchTier } val naturalOrder = compareBy<IndexEntry, String>(NaturalStringComparator) { it.word }
.thenBy { it.exactMatch } val result = ArrayList<IndexEntry>(size)
.thenBy { it.charCount } for (bucket in buckets) {
.thenBy(NaturalStringComparator) { it.word } if (bucket == null) continue
if (bucket.size > 1) bucket.sortWith(naturalOrder)
result.addAll(bucket)
}
return result.groupNumberedSeries(naturalOrder)
}
private fun List<IndexEntry>.groupNumberedSeries(
naturalOrder: Comparator<IndexEntry>,
): List<IndexEntry> {
val groups = LinkedHashMap<NumberedSeriesKey, MutableList<Int>>()
for (index in indices) {
val entry = this[index]
val range = naturalNumberRange(entry.word) ?: continue
val key = NumberedSeriesKey(
dictionaryPath = entry.dictionaryPath,
prefix = entry.word.substring(0, range.first),
suffix = entry.word.substring(range.last + 1),
) )
.map { it.entry } groups.getOrPut(key) { ArrayList() }.add(index)
}
val seriesAtPosition = HashMap<Int, List<IndexEntry>>()
val groupedPositions = BooleanArray(size)
for (indexes in groups.values) {
if (indexes.size < 2) continue
val series = ArrayList<IndexEntry>(indexes.size)
for (index in indexes) {
series.add(this[index])
groupedPositions[index] = true
}
series.sortWith(naturalOrder)
seriesAtPosition[indexes.first()] = series
}
if (seriesAtPosition.isEmpty()) return this
val result = ArrayList<IndexEntry>(size)
for (index in indices) {
seriesAtPosition[index]?.let { result.addAll(it) }
if (!groupedPositions[index]) result.add(this[index])
}
return result
} }
@@ -112,9 +112,7 @@ class SearchViewModel(
Pager( Pager(
config = PagingConfig( config = PagingConfig(
pageSize = 12, pageSize = 12,
prefetchDistance = 1, enablePlaceholders = false
enablePlaceholders = false,
initialLoadSize = 12
), ),
pagingSourceFactory = { pagingSourceFactory = {
IndexEntryPagingSource( IndexEntryPagingSource(