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 =
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 =
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
}
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++
j++
}
@@ -5,10 +5,9 @@ import androidx.paging.PagingState
import com.example.research.core.domain.model.Dictionary
import com.example.research.core.domain.model.IndexEntry
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.SearchRankingContext
import com.example.research.data.parser.rankBySearchRelevance
import com.example.research.data.parser.sortByCharCountThenNatural
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
@@ -68,9 +67,8 @@ class IndexEntryPagingSource(
}
}
val normalizedQuery = query.sanitizeQuery().lowercase().trim()
val ranked = rawResults
.rankBySearchRelevance(SearchRankingContext(normalizedQuery))
.sortByCharCountThenNatural()
.distinctBy { Triple(it.dictionaryPath, it.word, it.offset.value) }
LoadResult.Page(
@@ -122,9 +122,7 @@ class IndexSearcher(private val context: Context) {
}
}
}
(prefixMatches + substringMatches)
.rankBySearchRelevance(SearchRankingContext(normalizedQuery, foldedQuery))
.distinctBy { it.articleKey() }
(prefixMatches + substringMatches).distinctBy { it.articleKey() }
}
resultsCache.put(cacheKey, 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.util.NaturalStringComparator
import com.example.research.core.util.foldLatinDiacritics
import com.example.research.core.util.naturalNumberRange
internal data class SearchRankingContext(
val normalizedQuery: String,
val foldedQuery: String = normalizedQuery.foldLatinDiacritics(),
private data class NumberedSeriesKey(
val dictionaryPath: String,
val prefix: String,
val suffix: String,
)
private data class SortKey(
val matchTier: Int,
val exactMatch: Int,
val charCount: Int,
val word: String,
val entry: IndexEntry,
)
internal fun List<IndexEntry>.rankBySearchRelevance(
ranking: SearchRankingContext
): List<IndexEntry> {
internal fun List<IndexEntry>.sortByCharCountThenNatural(): List<IndexEntry> {
if (size < 2) return this
return map { entry ->
val word = entry.word
val charCounts = IntArray(size)
var minCount = Int.MAX_VALUE
var maxCount = Int.MIN_VALUE
for (i in indices) {
val entry = this[i]
val displayKey = entry.originalWord
.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(
matchTier = when {
!entry.isAlias && word.startsWith(ranking.normalizedQuery) -> 0
entry.isAlias && word.startsWith(ranking.foldedQuery) -> 1
!entry.isAlias && word.foldLatinDiacritics().startsWith(ranking.foldedQuery) -> 1
else -> 2
},
exactMatch = if (word == ranking.normalizedQuery) 0 else 1,
charCount = displayKey.codePointCount(0, displayKey.length),
word = word,
entry = entry,
)
val buckets = arrayOfNulls<ArrayList<IndexEntry>>(maxCount - minCount + 1)
for (i in indices) {
val bucketIndex = charCounts[i] - minCount
(buckets[bucketIndex] ?: ArrayList<IndexEntry>().also { buckets[bucketIndex] = it })
.add(this[i])
}
.sortedWith(
compareBy<SortKey> { it.matchTier }
.thenBy { it.exactMatch }
.thenBy { it.charCount }
.thenBy(NaturalStringComparator) { it.word }
val naturalOrder = compareBy<IndexEntry, String>(NaturalStringComparator) { it.word }
val result = ArrayList<IndexEntry>(size)
for (bucket in buckets) {
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(
config = PagingConfig(
pageSize = 12,
prefetchDistance = 1,
enablePlaceholders = false,
initialLoadSize = 12
enablePlaceholders = false
),
pagingSourceFactory = {
IndexEntryPagingSource(