Merge pull request #190 from yunyingk/feat/docs-fuzzy-search
CI / validate (push) Canceled after 0s

feat(docs): 支持多词分词模糊检索与匹配依据片段高亮展示
This commit is contained in:
yunyingk authored and GitHub committed 2026-11-16 16:44:19 +08:00
commit 1c5d6153a2
4 files changed
+157 -34

No files matched your search

+19 -7
View File
@@ -182,6 +182,7 @@ export async function handleDocsCommand(
path: item.path,
url: item.url,
permalink: item.permalink,
matchReason: item.matchReason || undefined,
}));
return {
stdout: printJson(
@@ -208,14 +209,25 @@ export async function handleDocsCommand(
};
}
const rows = searchRes.items.map((item) => [
item.method || "DOC",
item.path || item.url,
item.title,
item.category,
]);
const hasKeyword = Boolean(keyword);
const headers = hasKeyword
? ["Method", "Path / URL", "标题", "分类", "匹配依据"]
: ["Method", "Path / URL", "标题", "分类"];
const table = printTable(["Method", "Path / URL", "标题", "分类"], rows);
const rows = searchRes.items.map((item) => {
const base = [
item.method || "DOC",
item.path || item.url,
item.title,
item.category,
];
if (hasKeyword) {
base.push(item.matchReason || "-");
}
return base;
});
const table = printTable(headers, rows);
const filterDesc = [
keyword ? `关键词: '${keyword}'` : "",
category ? `分类: '${category}'` : "",
+8
View File
@@ -109,6 +109,14 @@ describe("Docs Domain - 开放平台文档域", () => {
expect(res.total).toBeGreaterThanOrEqual(1);
expect(res.items[0]?.path).toBe("/api/openapi/v1/roleDefGroups");
expect(res.items[0]?.title).toBe("查询角色组和角色");
expect(res.items[0]?.matchReason).toBeDefined();
});
it("searchDocs 支持多词分词与跨正文/参数模糊检索", async () => {
const res = await searchDocs({ keyword: "员工 手机" });
expect(res.total).toBeGreaterThanOrEqual(1);
expect(res.items.some((i) => i.title.includes("员工"))).toBe(true);
expect(res.items[0]?.matchReason).toBeDefined();
});
it("searchDocs 支持按分类与 HTTP 方法精确过滤", async () => {
+129 -27
View File
@@ -49,43 +49,146 @@ export async function getDocsCatalog(options?: {
}
/**
* 计算文档项与搜索关键词的相关度得分
* 计算文档项与搜索关键词的相关度得分,并生成高亮命中摘要
*/
function scoreDocItem(item: OpenApiDocItem, queryLower: string): number {
function evaluateDocMatch(
item: OpenApiDocItem,
rawKeyword: string
): { item: OpenApiDocItem; score: number } | null {
const queryLower = rawKeyword.trim().toLowerCase();
if (!queryLower) return null;
const tokens = queryLower.split(/[\s,+/]+/).filter(Boolean);
if (tokens.length === 0) return null;
let score = 0;
const matchReasons: string[] = [];
const pathLower = (item.path || "").toLowerCase();
const titleLower = item.title.toLowerCase();
const categoryLower = item.category.toLowerCase();
const urlLower = item.url.toLowerCase();
const paramLower = (item.parameters || "").toLowerCase();
const curlLower = (item.curl || "").toLowerCase();
const respLower = (item.responseSample || "").toLowerCase();
const allSectionsText = item.sections.map((s) => s.content).join(" ");
const sectionsLower = allSectionsText.toLowerCase();
// 路径完全匹配
if (pathLower === queryLower) score += 100;
else if (pathLower.includes(queryLower)) score += 60;
// 1. 完整短语匹配加分 (Phrase match)
if (queryLower.length > 1) {
if (pathLower === queryLower) {
score += 120;
matchReasons.push("路径完全匹配");
} else if (pathLower.includes(queryLower)) {
score += 80;
matchReasons.push(`路径包含 "${queryLower}"`);
}
// 标题完全匹配或包含
if (titleLower === queryLower) score += 80;
else if (titleLower.includes(queryLower)) score += 40;
if (titleLower === queryLower) {
score += 100;
matchReasons.push("标题完全匹配");
} else if (titleLower.includes(queryLower)) {
score += 60;
matchReasons.push(`标题包含 "${queryLower}"`);
}
// 分类完全匹配或包含
if (categoryLower === queryLower) score += 50;
else if (categoryLower.includes(queryLower)) score += 20;
if (categoryLower.includes(queryLower)) {
score += 40;
matchReasons.push(`模块: ${item.category}`);
}
// URL 路径包含
if (urlLower.includes(queryLower)) score += 30;
if (paramLower.includes(queryLower)) {
score += 45;
const idx = paramLower.indexOf(queryLower);
const snippet = (item.parameters || "")
.substring(Math.max(0, idx - 12), Math.min(item.parameters?.length || 0, idx + 30))
.replace(/\s+/g, " ");
matchReasons.push(`参数规格: ...${snippet}...`);
}
// CURL 或参数定义中出现
if (item.curl && item.curl.toLowerCase().includes(queryLower)) score += 25;
if (item.parameters && item.parameters.toLowerCase().includes(queryLower)) score += 20;
// 正文段落包含
for (const s of item.sections) {
if (s.content.toLowerCase().includes(queryLower)) {
score += 10;
break;
if (sectionsLower.includes(queryLower)) {
score += 35;
const idx = sectionsLower.indexOf(queryLower);
const snippet = allSectionsText
.substring(Math.max(0, idx - 12), Math.min(allSectionsText.length, idx + 30))
.replace(/\s+/g, " ");
matchReasons.push(`正文段落: ...${snippet}...`);
}
}
return score;
// 2. Token 分词逐项匹配 (Multi-token match)
let tokensMatched = 0;
for (const token of tokens) {
let tokenMatched = false;
if (pathLower.includes(token)) {
score += 30;
tokenMatched = true;
if (!matchReasons.some((r) => r.includes(token))) {
matchReasons.push(`路径含 "${token}"`);
}
}
if (titleLower.includes(token)) {
score += 25;
tokenMatched = true;
if (!matchReasons.some((r) => r.includes(token))) {
matchReasons.push(`标题含 "${token}"`);
}
}
if (categoryLower.includes(token)) {
score += 20;
tokenMatched = true;
if (!matchReasons.some((r) => r.includes(token))) {
matchReasons.push(`分类含 "${token}"`);
}
}
if (paramLower.includes(token)) {
score += 20;
tokenMatched = true;
if (!matchReasons.some((r) => r.includes(token))) {
const idx = paramLower.indexOf(token);
const snippet = (item.parameters || "")
.substring(Math.max(0, idx - 10), Math.min(item.parameters?.length || 0, idx + 25))
.replace(/\s+/g, " ");
matchReasons.push(`参数: ...${snippet}...`);
}
}
if (sectionsLower.includes(token)) {
score += 15;
tokenMatched = true;
if (!matchReasons.some((r) => r.includes(token))) {
const idx = sectionsLower.indexOf(token);
const snippet = allSectionsText
.substring(Math.max(0, idx - 10), Math.min(allSectionsText.length, idx + 25))
.replace(/\s+/g, " ");
matchReasons.push(`正文: ...${snippet}...`);
}
}
if (curlLower.includes(token) || respLower.includes(token)) {
score += 15;
tokenMatched = true;
if (!matchReasons.some((r) => r.includes(token))) {
matchReasons.push(`请求/响应含 "${token}"`);
}
}
if (tokenMatched) tokensMatched++;
}
// 多词全部命中奖励 (All-tokens match bonus)
if (tokens.length > 1 && tokensMatched === tokens.length) {
score += 50;
}
if (score <= 0 || tokensMatched === 0) return null;
const matchReason = matchReasons.slice(0, 2).join(" | ");
return {
item: {
...item,
matchReason,
},
score,
};
}
/**
@@ -123,10 +226,9 @@ export async function searchDocs(
// 4. 关键词打分与排序
const rawKeyword = query.keyword?.trim();
if (rawKeyword) {
const keywordLower = rawKeyword.toLowerCase();
const scored = items
.map((item) => ({ item, score: scoreDocItem(item, keywordLower) }))
.filter((entry) => entry.score > 0)
.map((item) => evaluateDocMatch(item, rawKeyword))
.filter((entry): entry is { item: OpenApiDocItem; score: number } => entry !== null)
.sort((a, b) => b.score - a.score);
items = scored.map((entry) => entry.item);
+1
View File
@@ -19,6 +19,7 @@ export const OpenApiDocItemSchema = z.object({
parameters: z.string().optional(),
curl: z.string().optional(),
responseSample: z.string().optional(),
matchReason: z.string().optional(),
});
export const DocCatalogSchema = z.object({