///|
/// n-gram 倒排索引:只用来**裁剪候选**,不改变结果集。
///
/// 建索引时把每个候选的 `key` 文本拆成码点 n-gram,记录「gram → 候选下标」,
/// 并缓存文本与码点长度(`search` 不再接收 `key`,也不必每次重新量长度)。
/// 查询时用 query 的 n-gram 取并集当候选池,池内候选算精确分数;池外候选先用
/// 长度 / q-gram 上界判断「是否可能进前 k」,可能才补算精确分数。
/// 排序复用 `topk.mbt` 里的同一个最小堆,与 `top_k` 的语义完全一致。
pub(all) struct Index[A] {
choices : Array[A]
keys : Array[String]
lens : Array[Int32]
grams : Map[String, Array[Int32]]
n : Int32
}
///|
/// 把文本拆成码点 n-gram(长度不足 n 时没有 gram,返回空数组)。
fn code_point_ngrams(text : String, n : Int32) -> Array[String] {
let chars = text.to_array()
let out : Array[String] = []
if n <= 0 || chars.length() < n {
return out
}
for i = 0; i <= chars.length() - n; i = i + 1 {
out.push(String::from_array(chars[i:i + n]))
}
out
}
///|
/// 建索引:`n` 是 n-gram 长度(常用 3,小于 1 时按 1 处理),`key` 取候选上参与比较的文本。
pub fn[A] Index::build(
choices : Array[A],
n : Int32,
key : (A) -> String,
) -> Index[A] {
let grams : Map[String, Array[Int32]] = Map([])
let keys : Array[String] = Array(capacity=choices.length())
let lens : Array[Int32] = Array(capacity=choices.length())
let step = if n < 1 { 1 } else { n }
for i = 0; i < choices.length(); i = i + 1 {
let text = key(choices[i])
keys.push(text)
lens.push(text.to_array().length())
let pieces = code_point_ngrams(text, step)
for j = 0; j < pieces.length(); j = j + 1 {
match grams.get(pieces[j]) {
None => {
let postings : Array[Int32] = [i]
grams.set(pieces[j], postings)
}
Some(postings) => postings.push(i)
}
}
}
{ choices, keys, lens, grams, n: step, }
}
///|
/// 两个长度的绝对差。
fn abs_diff_int(a : Int32, b : Int32) -> Int32 {
if a > b {
a - b
} else {
b - a
}
}
///|
/// q-gram 下界:与 query **没有任何共同 n-gram** 时,距离至少是 `(len_query - n + 1)/n`。
///
/// 依据:一次编辑最多破坏 n 个 n-gram,而 query 的 n-gram 共 `len_query - n + 1` 个,
/// 要一个都不剩,至少需要这么多次编辑。对 Levenshtein / LCSseq / Indel 成立
/// (后两者的距离不小于 Levenshtein 距离);对 DamerauLevenshtein / OSA 不成立
/// (一次对换只花 1 次编辑,却会破坏超过 n 个 gram),因此这两个算法只用长度下界。
fn qgram_lower_bound(query_len : Int32, n : Int32) -> Double {
if n <= 0 || query_len < n {
0.0
} else {
(query_len - n + 1).to_double() / n.to_double()
}
}
///|
/// 由距离下界换算成归一化相似度上界。
fn similarity_upper_bound(distance_lower : Double, denom : Int32) -> Double {
if denom == 0 {
1.0
} else {
1.0 - distance_lower / denom.to_double()
}
}
///|
/// 长度 / q-gram 上界:池外候选的相似度不会超过这个值。
///
/// 返回 `-1.0` 表示「这条候选在打分阶段就会被丢掉」(Hamming 遇到不等长),
/// 不必为它算精确分数。Jaro / JaroWinkler 没有可用的下界,恒返回 `1.0`,
/// 因此这两个算法上池外候选一律要补算,等于全量扫描。
fn length_upper_bound(
metric : Metric,
cand_len : Int32,
query_len : Int32,
n : Int32,
) -> Double {
let diff = abs_diff_int(cand_len, query_len).to_double()
let qgram = qgram_lower_bound(query_len, n)
let max_len = max_int(cand_len, query_len)
let sum_len = cand_len + query_len
match metric {
Metric::Levenshtein =>
similarity_upper_bound(if diff > qgram { diff } else { qgram }, max_len)
Metric::LCSseq =>
similarity_upper_bound(if diff > qgram { diff } else { qgram }, max_len)
Metric::Indel =>
similarity_upper_bound(if diff > qgram { diff } else { qgram }, sum_len)
Metric::DamerauLevenshtein => similarity_upper_bound(diff, max_len)
Metric::OSA => similarity_upper_bound(diff, max_len)
Metric::Hamming => if cand_len == query_len { 1.0 } else { -1.0 }
Metric::Jaro => 1.0
Metric::JaroWinkler => 1.0
}
}
///|
/// 对单条候选打分并入堆。
fn[A] Index::offer_candidate(
self : Index[A],
heap : TopKHeap[A],
index : Int32,
query : String,
score_cutoff : Double,
metric : Metric,
) -> Unit {
match metric.normalized_similarity_opt(self.keys[index], query) {
None => ()
Some(score) =>
if score >= score_cutoff {
heap.offer(score, index, self.choices[index])
}
}
}
///|
/// 全量扫描(与 `top_k` 的打分、入堆、排序完全一致),候选池为空时用它兜底。
fn[A] Index::scan_all(
self : Index[A],
query : String,
limit : Int32,
score_cutoff : Double,
metric : Metric,
) -> Array[(A, Double)] {
let heap = TopKHeap::new(limit)
for i = 0; i < self.choices.length(); i = i + 1 {
self.offer_candidate(heap, i, query, score_cutoff, metric)
}
heap.into_result()
}
///|
/// 用 query 的 n-gram 命中集合作候选池,返回池内下标与「是否在池内」的标记数组。
fn[A] Index::build_pool(
self : Index[A],
query : String,
) -> (Array[Int32], Array[Bool]) {
let total = self.choices.length()
let marks : Array[Bool] = Array::make(total, false)
let pool : Array[Int32] = []
let pieces = code_point_ngrams(query, self.n)
for i = 0; i < pieces.length(); i = i + 1 {
match self.grams.get(pieces[i]) {
None => ()
Some(postings) =>
for j = 0; j < postings.length(); j = j + 1 {
let idx = postings[j]
if !marks[idx] {
marks[idx] = true
pool.push(idx)
}
}
}
}
(pool, marks)
}
///|
/// 当前入选门槛:堆满时取堆顶分数,没满时取 `score_cutoff`(分数低于它的候选一律不要)。
fn[A] current_threshold(heap : TopKHeap[A], score_cutoff : Double) -> Double {
if heap.is_full() {
heap.worst_score()
} else {
score_cutoff
}
}
///|
/// 在索引上检索:结果与 `top_k(choices, query, k, score_cutoff, metric, key)` 逐项相同。
///
/// 流程:query 的 n-gram 取候选池 → 池内候选算精确分数 → 池外候选只用上界判断,
/// 上界不低于门槛才补算精确分数。上界判定是逐条做的,因此裁剪不会改变结果集:
/// 被跳过的候选,其分数严格小于门槛,既不可能高于堆内任何一条,也不可能与门槛同分。
pub fn[A] Index::search(
self : Index[A],
query : String,
k : Int32,
score_cutoff : Double,
metric : Metric,
) -> Array[(A, Double)] {
let total = self.choices.length()
if k <= 0 || total == 0 {
return []
}
let limit = min_int(k, total)
let (_, marks) = self.build_pool(query)
let mut pool_size = 0
for i = 0; i < total; i = i + 1 {
if marks[i] {
pool_size = pool_size + 1
}
}
// 候选池为空(query 短于 n,或 gram 全部未命中):必须回退全量扫描
if pool_size == 0 {
return self.scan_all(query, limit, score_cutoff, metric)
}
let heap = TopKHeap::new(limit)
let query_len = code_point_len(query)
for i = 0; i < total; i = i + 1 {
if marks[i] {
self.offer_candidate(heap, i, query, score_cutoff, metric)
} else {
let bound = length_upper_bound(metric, self.lens[i], query_len, self.n)
if bound >= current_threshold(heap, score_cutoff) {
self.offer_candidate(heap, i, query, score_cutoff, metric)
}
}
}
heap.into_result()
}