在米米商聊的项目群里找验收资料,预期看到验收报告、线缆清单和签字页。设计语义搜索时,通常会把长文件切成片段,搜索可能先命中验收报告的第 2、3、4 页。若直接把片段排名当作文件列表,三个位置就全给了一份报告。
文件卡片只占一个位置,仍保留命中的页码
检索可保留片段级排序,文件列表则按附件 ID 归组。示例取每份附件最靠前的片段作为入口。两个重名文件仍按独立的附件 ID 处理。对结果按字段归组、选每组最靠前的命中,也可参考 Elasticsearch 的结果折叠。 Elastic 折叠搜索结果
| 原片段名次 | 附件 ID | 文件与命中位置 |
|---|---|---|
| 1 | A | 验收报告,第 2 页 |
| 2 | A | 验收报告,第 3 页 |
| 3 | A | 验收报告,第 4 页 |
| 4 | B | 线缆清单,第 1 页 |
| 5 | C | 签字页,第 1 页 |

先截前三条片段再折叠,只剩 A。拿到五个候选片段后,边扫描边归组,可得到 A、B、C 三个文件入口,同时保留 A 的第 2 页。需要展示更多命中页时,可把它们收在同一张卡片下。
本地复现:改变截取时机
将下列代码保存为 collapse-chunks.cjs,运行 node collapse-chunks.cjs。输入是已经排好顺序的候选片段。示例输出附件 ID、片段 ID 和页码,不改动原列表。这里使用同一文件版本的附件 ID 归组。
js
function topAttachments(rankedChunks, limit) {
if (!Number.isSafeInteger(limit) || limit < 1) {
throw new RangeError("文件结果上限须为正整数");
}
const seen = new Set();
const result = [];
for (const hit of rankedChunks) {
if (typeof hit.attachmentId !== "string" || !hit.attachmentId.trim()) {
throw new TypeError("候选片段缺少附件 ID");
}
if (seen.has(hit.attachmentId)) continue;
seen.add(hit.attachmentId);
result.push({
attachmentId: hit.attachmentId,
chunkId: hit.chunkId,
page: hit.page
});
if (result.length === limit) break;
}
return result;
}
const chunks = [
{ attachmentId: "A", chunkId: "a2", page: 2 },
{ attachmentId: "A", chunkId: "a3", page: 3 },
{ attachmentId: "A", chunkId: "a4", page: 4 },
{ attachmentId: "B", chunkId: "b1", page: 1 },
{ attachmentId: "C", chunkId: "c1", page: 1 }
];
const show = hits => hits.map(hit => hit.attachmentId + " 第" + hit.page + "页").join(",");
console.log("先截片段", show(topAttachments(chunks.slice(0, 3), 3)));
console.log("先折叠", show(topAttachments(chunks, 3)));
text
先截片段 A 第2页
先折叠 A 第2页,B 第1页,C 第1页
候选窗口里只有一个文件时,折叠后也只能返回一个
如果检索端只返回前三个片段,展示层无法恢复它没收到的 B 和 C。联调时分别记录「取了多少片段」和「折叠后剩多少附件」,必要时扩大候选窗口或让检索端按附件分组。扩大窗口会多取候选,可以用具有多个相关附件的查询观察收益。上次文章的 Recall@3 和 MRR@3 可直接用在这类按文件展示的结果上。 按附件 ID 评测搜索结果
本篇用 Node.js v24.22.3 运行自造排名,验证候选不足、ID 缺失、首个片段保留和输出顺序。示例只验证片段到文件列表的转换,未调用向量模型或接入产品。
创作说明:本文由 AI 辅助整理资料、编写示例并运行本地验证,文件和配图均为自造。