Refactor fuzzy search engine into strategy functions

This commit is contained in:
gitea committed 2026-10-02 16:32:39 +08:00
1 parent 482ebf57b5
commit e4b1eea5a9
1 file changed
+301 -185
+301 -185
View File
@@ -36,6 +36,10 @@ export interface MatchScoreResult {
reason: MatchReason;
}
// ---------------------------------------------------------------------------
// Edit-distance & character-order primitives
// ---------------------------------------------------------------------------
/**
* Standard Levenshtein distance between two strings.
*/
@@ -95,6 +99,24 @@ export function minSubstringLevenshtein(query: string, target: string): number {
return min;
}
/**
* Checks if all characters of `query` appear in order inside `target` (subsequence).
*/
export function isSubsequence(query: string, target: string): boolean {
if (!query || !target) return false;
let qIdx = 0;
for (let tIdx = 0; tIdx < target.length && qIdx < query.length; tIdx += 1) {
if (query[qIdx] === target[tIdx]) {
qIdx += 1;
}
}
return qIdx === query.length;
}
// ---------------------------------------------------------------------------
// Pinyin normalization & Chinese segmentation
// ---------------------------------------------------------------------------
/**
* Normalizes Chinese text to toneless pinyin with fuzzy sound rules:
* - Retroflex vs flat consonants: zh -> z, ch -> c, sh -> s
@@ -120,20 +142,6 @@ export function normalizeFuzzyPinyin(str: string): string {
.join("");
}
/**
* Checks if all characters of `query` appear in order inside `target` (subsequence).
*/
export function isSubsequence(query: string, target: string): boolean {
if (!query || !target) return false;
let qIdx = 0;
for (let tIdx = 0; tIdx < target.length && qIdx < query.length; tIdx += 1) {
if (query[qIdx] === target[tIdx]) {
qIdx += 1;
}
}
return qIdx === query.length;
}
function searchTerms(value: string): string[] {
const chunks = value.trim().toLowerCase().match(/[\u4e00-\u9fa5]+|[a-z0-9]+/g) ?? [];
return chunks.flatMap((chunk) => {
@@ -172,42 +180,135 @@ function searchWords(value: string): string[] {
return words;
}
function matchTokenizedQuery(query: string, target: string): MatchScoreResult {
if (!/[\u4e00-\u9fa5]/.test(query)) {
return { matched: false, score: 0, reason: "none" };
}
const queryWords = searchWords(query);
const wordMatches = queryWords.map((word) => fuzzyMatchString(word, target).matched);
if (queryWords.length >= 2 && wordMatches.filter(Boolean).length >= queryWords.length - 1) {
const allWordsMatch = queryWords.every((word, index) => wordMatches[index] || (
// A second matching word supplies context for a typo in a two-character
// name, e.g. "瑞泰 半导体" -> "钰泰半导体". Single-word searches stay conservative.
/^[\u4e00-\u9fa5]{2}$/.test(word) && minSubstringLevenshtein(word, target) <= 1
));
if (allWordsMatch) return { matched: true, score: 0.76, reason: "tokens" };
}
const queryTerms = searchTerms(query);
if (queryTerms.length < 2) return { matched: false, score: 0, reason: "none" };
const matchedTerms = queryTerms.filter((term) => fuzzyMatchString(term, target).matched);
if (matchedTerms.length > 0) {
const coverage = matchedTerms.length / queryTerms.length;
return {
matched: true,
score: queryWords.length >= 2 ? Math.min(0.64, 0.56 + coverage * 0.2) : 0.56 + coverage * 0.2,
reason: "tokens"
};
}
// ---------------------------------------------------------------------------
// fuzzyMatchString: strategy cascade
// ---------------------------------------------------------------------------
function noMatch(): MatchScoreResult {
return { matched: false, score: 0, reason: "none" };
}
interface PinyinPair {
query: string;
target: string;
}
/**
* Precomputed per (query, target) pair so every strategy can share the work.
*/
interface MatchContext {
targetHasChinese: boolean;
queryHasChinese: boolean;
/** Fuzzy pinyin of both sides, or null when neither side contains Chinese. */
fuzzyPinyin: PinyinPair | null;
maxDistance: number;
}
function buildMatchContext(
normQuery: string,
normTarget: string,
options: FuzzyMatchOptions
): MatchContext {
const targetHasChinese = /[\u4e00-\u9fa5]/.test(normTarget);
const queryHasChinese = /[\u4e00-\u9fa5]/.test(normQuery);
return {
targetHasChinese,
queryHasChinese,
fuzzyPinyin:
targetHasChinese || queryHasChinese
? { target: normalizeFuzzyPinyin(normTarget), query: normalizeFuzzyPinyin(normQuery) }
: null,
// Allowed edit distance based on query length:
// - <= 2: 0 (no fuzzy edits to prevent excessive false positives)
// - 3..5: 1 (missing 1 letter or 1 typo)
// - >= 6: 2 (missing 1-2 letters)
maxDistance: options.maxDistance ?? (normQuery.length <= 2 ? 0 : normQuery.length <= 5 ? 1 : 2)
};
}
/** Initials / Acronym match (e.g. "xzh" matches "谢子豪", "sc" matches "生产"). */
function matchByInitials(query: string, target: string, ctx: MatchContext): MatchScoreResult | null {
if (!ctx.targetHasChinese || query.length < 2) return null;
const targetInitials = pinyin(target, { pattern: "first", toneType: "none", type: "array" })
.join("")
.toLowerCase();
if (targetInitials.includes(query)) {
return { matched: true, score: 0.9, reason: "initials" };
}
return null;
}
/** Pinyin-pro built-in match (handles full/partial pinyin matching against Chinese targets). */
function matchByPinyin(query: string, target: string, ctx: MatchContext): MatchScoreResult | null {
if (!ctx.targetHasChinese) return null;
try {
const pm = pinyinMatch(target, query, { precision: "start" });
if (pm && pm.length > 0) {
return { matched: true, score: 0.88, reason: "pinyin" };
}
} catch {
// ignore match errors if non-standard regex chars
}
return null;
}
/** Fuzzy Pinyin & Homophones (同音字、前后鼻音、平翘舌音). */
function matchByFuzzyPinyin(ctx: MatchContext): MatchScoreResult | null {
const pair = ctx.fuzzyPinyin;
if (!pair || pair.query.length < 2) return null;
if (pair.target.includes(pair.query)) {
return { matched: true, score: 0.85, reason: "fuzzy_pinyin" };
}
return null;
}
/** Missing letter / Typo tolerance (Levenshtein Distance), on raw strings then on fuzzy pinyin. */
function matchByEditDistance(
query: string,
target: string,
ctx: MatchContext
): MatchScoreResult | null {
if (ctx.maxDistance <= 0) return null;
// Check raw string distance
const rawDist = minSubstringLevenshtein(query, target);
if (rawDist <= ctx.maxDistance) {
return { matched: true, score: Math.max(0.6, 0.8 - rawDist * 0.1), reason: "levenshtein" };
}
// Check fuzzy pinyin distance (e.g. pinyin with 1 missing letter)
const pair = ctx.fuzzyPinyin;
if (pair && pair.query.length >= 3 && pair.target.length >= 3) {
const pinyinDist = minSubstringLevenshtein(pair.query, pair.target);
if (pinyinDist <= ctx.maxDistance) {
return { matched: true, score: Math.max(0.6, 0.78 - pinyinDist * 0.1), reason: "levenshtein" };
}
}
return null;
}
/** Subsequence match (loose character order, min query length 3). */
function matchBySubsequence(
query: string,
target: string,
ctx: MatchContext
): MatchScoreResult | null {
if (query.length < 3) return null;
if (isSubsequence(query, target)) {
return { matched: true, score: 0.65, reason: "subsequence" };
}
const pair = ctx.fuzzyPinyin;
if (pair && isSubsequence(pair.query, pair.target)) {
return { matched: true, score: 0.65, reason: "subsequence" };
}
return null;
}
/**
* Core fuzzy string match engine:
* Evaluates match across exact, substring, initials, pinyin, homophone/fuzzy pinyin,
* sliding-window edit distance (missing/typo tolerance), and character subsequence.
* Strategies run in priority order; the first hit wins.
*/
export function fuzzyMatchString(
query: string,
@@ -218,120 +319,96 @@ export function fuzzyMatchString(
const normTarget = target.trim().toLowerCase();
if (!normQuery || !normTarget) {
return { matched: false, score: 0, reason: "none" };
return noMatch();
}
// 1. Exact match
// Exact match
if (normTarget === normQuery) {
return { matched: true, score: 1.0, reason: "exact" };
}
// 2. Substring match
// Substring match
if (normTarget.includes(normQuery)) {
return { matched: true, score: 0.95, reason: "substring" };
}
// If strict mode is requested, only exact or substring matches are accepted.
if (options.strict) {
return { matched: false, score: 0, reason: "none" };
return noMatch();
}
const targetHasChinese = /[\u4e00-\u9fa5]/.test(normTarget);
const queryHasChinese = /[\u4e00-\u9fa5]/.test(normQuery);
// 3. Initials / Acronym match (e.g. "xzh" matches "谢子豪", "sc" matches "生产")
if (targetHasChinese && normQuery.length >= 2) {
const targetInitials = pinyin(normTarget, { pattern: "first", toneType: "none", type: "array" })
.join("")
.toLowerCase();
if (targetInitials.includes(normQuery)) {
return { matched: true, score: 0.9, reason: "initials" };
}
}
// 4. Pinyin-pro built-in match (handles full/partial pinyin matching against Chinese targets)
if (targetHasChinese) {
try {
const pm = pinyinMatch(normTarget, normQuery, { precision: "start" });
if (pm && pm.length > 0) {
return { matched: true, score: 0.88, reason: "pinyin" };
}
} catch {
// ignore match errors if non-standard regex chars
}
}
// 5. Fuzzy Pinyin & Homophones (同音字、前后鼻音、平翘舌音)
let targetFuzzyPinyin = "";
let queryFuzzyPinyin = "";
if (targetHasChinese || queryHasChinese) {
targetFuzzyPinyin = normalizeFuzzyPinyin(normTarget);
queryFuzzyPinyin = normalizeFuzzyPinyin(normQuery);
if (queryFuzzyPinyin.length >= 2 && targetFuzzyPinyin.includes(queryFuzzyPinyin)) {
return { matched: true, score: 0.85, reason: "fuzzy_pinyin" };
}
}
// 6. Missing letter / Typo tolerance (Levenshtein Distance)
// Determine allowed distance based on query length:
// - <= 2: 0 (no fuzzy edits to prevent excessive false positives)
// - 3..5: 1 (missing 1 letter or 1 typo)
// - >= 6: 2 (missing 1-2 letters)
const defaultMaxDist = normQuery.length <= 2 ? 0 : normQuery.length <= 5 ? 1 : 2;
const maxAllowedDist = options.maxDistance ?? defaultMaxDist;
if (maxAllowedDist > 0) {
// Check raw string distance
const rawDist = minSubstringLevenshtein(normQuery, normTarget);
if (rawDist <= maxAllowedDist) {
return {
matched: true,
score: Math.max(0.6, 0.8 - rawDist * 0.1),
reason: "levenshtein"
};
}
// Check fuzzy pinyin distance (e.g. pinyin with 1 missing letter)
if (
(targetHasChinese || queryHasChinese) &&
queryFuzzyPinyin.length >= 3 &&
targetFuzzyPinyin.length >= 3
) {
const pinyinDist = minSubstringLevenshtein(queryFuzzyPinyin, targetFuzzyPinyin);
if (pinyinDist <= maxAllowedDist) {
return {
matched: true,
score: Math.max(0.6, 0.78 - pinyinDist * 0.1),
reason: "levenshtein"
};
}
}
}
// 7. Subsequence match (loose character order, min query length 3)
if (normQuery.length >= 3) {
if (
isSubsequence(normQuery, normTarget) ||
((targetHasChinese || queryHasChinese) && isSubsequence(queryFuzzyPinyin, targetFuzzyPinyin))
) {
return { matched: true, score: 0.65, reason: "subsequence" };
}
}
return { matched: false, score: 0, reason: "none" };
const context = buildMatchContext(normQuery, normTarget, options);
return (
matchByInitials(normQuery, normTarget, context) ??
matchByPinyin(normQuery, normTarget, context) ??
matchByFuzzyPinyin(context) ??
matchByEditDistance(normQuery, normTarget, context) ??
matchBySubsequence(normQuery, normTarget, context) ??
noMatch()
);
}
/**
* Matches an enterprise (`CorpConfig`) against a query across all its searchable fields,
* returning the highest match score and reason.
*/
export function matchCorp(
corp: CorpConfig,
// ---------------------------------------------------------------------------
// Tokenized Chinese query matching
// ---------------------------------------------------------------------------
/** Word-level pass: every segmented word matches the target (one typo tolerated via context). */
function matchQueryWords(queryWords: string[], target: string): MatchScoreResult | null {
if (queryWords.length < 2) return null;
const wordMatches = queryWords.map((word) => fuzzyMatchString(word, target).matched);
if (wordMatches.filter(Boolean).length < queryWords.length - 1) return null;
const allWordsMatch = queryWords.every((word, index) => wordMatches[index] || (
// A second matching word supplies context for a typo in a two-character
// name, e.g. "瑞泰 半导体" -> "钰泰半导体". Single-word searches stay conservative.
/^[\u4e00-\u9fa5]{2}$/.test(word) && minSubstringLevenshtein(word, target) <= 1
));
if (!allWordsMatch) return null;
return { matched: true, score: 0.76, reason: "tokens" };
}
/** Term-coverage pass: overlapping two-character terms of the query hit the target. */
function matchQueryTerms(
query: string,
options: FuzzyMatchOptions = {}
): MatchScoreResult {
const fields: Array<{ text: string | undefined; weight: number }> = [
queryWordCount: number,
target: string
): MatchScoreResult | null {
const queryTerms = searchTerms(query);
if (queryTerms.length < 2) return null;
const matchedTerms = queryTerms.filter((term) => fuzzyMatchString(term, target).matched);
if (matchedTerms.length === 0) return null;
const coverage = matchedTerms.length / queryTerms.length;
return {
matched: true,
score: queryWordCount >= 2 ? Math.min(0.64, 0.56 + coverage * 0.2) : 0.56 + coverage * 0.2,
reason: "tokens"
};
}
function matchTokenizedQuery(query: string, target: string): MatchScoreResult {
if (!/[\u4e00-\u9fa5]/.test(query)) {
return noMatch();
}
const queryWords = searchWords(query);
return matchQueryWords(queryWords, target) ?? matchQueryTerms(query, queryWords.length, target) ?? noMatch();
}
// ---------------------------------------------------------------------------
// Corp-level matching
// ---------------------------------------------------------------------------
interface CorpField {
text: string | undefined;
weight: number;
}
function corpSearchFields(corp: CorpConfig): CorpField[] {
return [
{ text: corp.name, weight: 1.2 },
{ text: corp.id, weight: 1.1 },
{ text: corp.source.staffId, weight: 1.0 },
@@ -346,63 +423,106 @@ export function matchCorp(
{ text: corp.source.type, weight: 0.8 },
{ text: (corp.source as any).provider, weight: 0.8 }
];
}
let bestScore = 0;
let bestReason: MatchReason = "none";
interface WeightedMatch {
score: number;
reason: MatchReason;
}
/** Keeps the higher-scoring candidate; ties stay with the earlier match. */
function strongerMatch(current: WeightedMatch, candidate: WeightedMatch): WeightedMatch {
return candidate.score > current.score ? candidate : current;
}
function matchCorpFields(
fields: CorpField[],
query: string,
options: FuzzyMatchOptions
): WeightedMatch {
let best: WeightedMatch = { score: 0, reason: "none" };
for (const field of fields) {
if (!field.text) continue;
const res = fuzzyMatchString(query, field.text, options);
if (res.matched) {
const weightedScore = res.score * field.weight;
if (weightedScore > bestScore) {
bestScore = weightedScore;
bestReason = res.reason;
}
best = strongerMatch(best, { score: res.score * field.weight, reason: res.reason });
}
}
return best;
}
// When a long Chinese query contains a compact enterprise name in order (for
// example, "苏州园区测绘" contains the leading "园测" of "园测信息科技股份有限公司"),
// retain that candidate as a lower-confidence abbreviation match. This is
// deliberately below exact/substring/pinyin matches and disabled in strict mode.
/**
* When a long Chinese query contains a compact enterprise name in order (for
* example, "苏州园区测绘" contains the leading "园测" of "园测信息科技股份有限公司"),
* retain that candidate as a lower-confidence abbreviation match. This is
* deliberately below exact/substring/pinyin matches and disabled in strict mode.
*/
function matchCorpAbbreviation(fields: CorpField[], query: string): WeightedMatch {
let best: WeightedMatch = { score: 0, reason: "none" };
const queryChinese = query.trim().match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
if (queryChinese.length < 3) return best;
for (const field of fields) {
if (!field.text) continue;
const targetChinese = field.text.match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
const prefix = targetChinese.slice(0, 2);
if (prefix.length < 2 || !isSubsequence(prefix, queryChinese)) continue;
best = strongerMatch(best, { score: 0.74 * field.weight, reason: "abbreviation" });
}
return best;
}
function matchCorpTokens(fields: CorpField[], query: string): WeightedMatch {
let best: WeightedMatch = { score: 0, reason: "none" };
for (const field of fields) {
if (!field.text) continue;
const res = matchTokenizedQuery(query, field.text);
if (res.matched) {
best = strongerMatch(best, { score: res.score * field.weight, reason: res.reason });
}
}
return best;
}
/**
* Matches an enterprise (`CorpConfig`) against a query across all its searchable fields,
* returning the highest match score and reason.
*/
export function matchCorp(
corp: CorpConfig,
query: string,
options: FuzzyMatchOptions = {}
): MatchScoreResult {
const fields = corpSearchFields(corp);
let best = matchCorpFields(fields, query, options);
if (!options.strict) {
const queryChinese = query.trim().match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
if (queryChinese.length >= 3) {
for (const field of fields) {
if (!field.text) continue;
const targetChinese = field.text.match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
const prefix = targetChinese.slice(0, 2);
if (prefix.length < 2 || !isSubsequence(prefix, queryChinese)) continue;
const weightedScore = 0.74 * field.weight;
if (weightedScore > bestScore) {
bestScore = weightedScore;
bestReason = "abbreviation";
}
}
}
for (const field of fields) {
if (!field.text) continue;
const res = matchTokenizedQuery(query, field.text);
if (res.matched) {
const weightedScore = res.score * field.weight;
if (weightedScore > bestScore) {
bestScore = weightedScore;
bestReason = res.reason;
}
}
}
best = strongerMatch(best, matchCorpAbbreviation(fields, query));
best = strongerMatch(best, matchCorpTokens(fields, query));
}
return {
matched: bestScore > 0,
score: bestScore,
reason: bestReason
matched: best.score > 0,
score: best.score,
reason: best.reason
};
}
// ---------------------------------------------------------------------------
// Corpus filtering & ranking
// ---------------------------------------------------------------------------
/**
* Once a strong candidate exists, suppress weak token-only suggestions. This
* keeps a query such as "苏州园区测绘" focused on the compact-name match
* instead of also returning every enterprise that merely contains "测绘".
*/
function suppressWeakMatches(scored: Array<{ corp: CorpConfig; score: number }>): CorpConfig[] {
const strongMatches = scored.filter((item) => item.score >= 0.8);
return (strongMatches.length > 0 ? strongMatches : scored).map((item) => item.corp);
}
/**
* Filters a list of enterprises using soft fuzzy search (or strict search if requested),
* and automatically sorts the matching results from highest relevance to lowest.
@@ -427,9 +547,5 @@ export function filterCorpsFuzzy(
// Sort by match score descending (highest confidence first)
scored.sort((a, b) => b.score - a.score);
// Once a strong candidate exists, suppress weak token-only suggestions. This
// keeps a query such as "苏州园区测绘" focused on the compact-name match
// instead of also returning every enterprise that merely contains "测绘".
const strongMatches = scored.filter((item) => item.score >= 0.8);
return (strongMatches.length > 0 ? strongMatches : scored).map((item) => item.corp);
return suppressWeakMatches(scored);
}