dacli(kb): CJK 检索 ILIKE 子串兜底 (优化 1/3)

problem: pg_trgm.similarity_threshold 默认 0.3, 对 3 字 CJK 查询
  (如"子代理") similarity 约 0.17 → `%` 操作符拒绝, 0 结果。
  同样影响 4-5 字短查询 (子代理派发)。

fix: _search.ts CJK path 改成 OR 三条件:
  1. content % $1 (trigram 模糊)
  2. content ILIKE '%q%' (内容子串, rank=0.5)
  3. section ILIKE '%q%' (段落名子串, rank=0.6, 优先级更高)
rank 取 GREATEST, 短查询靠 ILIKE 兜底, 长查询靠 trigram 模糊。

实测对比 (npx tsx src/cli.ts kb search <query>):
  "子代理"        0 → 2 results (rank 0.5, 命中 ssw-loop/踩坑教训)
  "子代理派发"    0 → 2 results
  "踩坑"          10 results (保持)
  "scanBasePackages"  2 results (ASCII 路径未受影响)
  "TC-B"            3 results (混合路径, ASCII 仍准)

配合: src/commands/kb/_schema.ts 加 pg_trgm 扩展 + GIN trgm 索引 (上轮已 commit 5da8cad)。

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
sswandClaude committed 2026-07-02 20:14:03 +08:00
1 parent 5da8cadb1a
commit a4adc94c8b
1 file changed
+11 -3
+11 -3
View File
@@ -60,17 +60,25 @@ export async function search(opts: SearchOptions): Promise<SearchResult[]> {
`;
params = [tsquery];
} else {
// CJK path: pg_trgm
// CJK path: pg_trgm (trigram similarity) + ILIKE (exact substring fallback)
// pg_trgm.similarity_threshold 默认 0.3, 对 3 字 CJK (similarity ≈ 0.17) 太严
// 双层覆盖: trigram 模糊匹配 + ILIKE 精确子串 (短查询兜底)
sql = `
SELECT e.id, d.domain, e.section, e.content,
similarity(e.content, $1) AS rank,
GREATEST(
similarity(e.content, $1),
CASE WHEN e.content ILIKE '%' || $1 || '%' THEN 0.5 ELSE 0 END,
CASE WHEN e.section ILIKE '%' || $1 || '%' THEN 0.6 ELSE 0 END
) AS rank,
COALESCE(
substring(e.content from greatest(1, position($1 in e.content) - 30) for 100),
substring(e.content from 1 for 100)
) AS snippet
FROM ${source} e
JOIN ${SCHEMA}.domains d ON d.id = e.domain_id
WHERE e.content % $1 OR e.section % $1
WHERE e.content % $1
OR e.content ILIKE '%' || $1 || '%'
OR e.section ILIKE '%' || $1 || '%'
`;
params = [q];
}