本地向量检索跑通后,还需要保存索引与“向量行号→资料 ID”的映射。FAISS 的 IndexFlatL2 适合用作精确检索入门:不需要训练索引,按平方欧氏距离返回近邻。索引文件本身不负责存储业务正文或访问权限。
用可手算向量验证链路
需要 Python、numpy 和可用的 faiss-cpu 包。下面三条二维向量是人为构造的数值样例,不是语义模型输出,也不是知识库检索效果测试。保存为 index_demo.py,在独立目录运行,避免覆盖正式索引。

python -m pip install numpy faiss-cpu
先查,再写盘并重载
import json
import numpy as np
import faiss
vectors = np.array([[0, 0], [1, 0], [3, 0]], dtype="float32")
doc_ids = ["doc-A", "doc-B", "doc-C"]
query = np.array([[0.9, 0]], dtype="float32")
index = faiss.IndexFlatL2(2)
index.add(vectors)
distances, positions = index.search(query, 2)
faiss.write_index(index, "demo.faiss")
with open("demo_ids.json", "w", encoding="utf-8") as f:
json.dump(doc_ids, f)
loaded = faiss.read_index("demo.faiss")
with open("demo_ids.json", encoding="utf-8") as f:
mapping = json.load(f)
after_distances, after_positions = loaded.search(query, 2)
assert loaded.ntotal == len(mapping) == 3
np.testing.assert_array_equal(positions, after_positions)
np.testing.assert_allclose(distances, after_distances)
for pos, distance in zip(after_positions[0], after_distances[0]):
if pos >= 0:
print(mapping[int(pos)], round(float(distance), 4))
核对距离与资料身份
验证应得到 doc-B 距离约 0.01、doc-A 约 0.81,重载前后位置和距离一致。这里返回平方距离,越小越近;不能按越大越相关排序。浮点输出末位可能不同,比较时用容差。
普通 IndexFlatL2 使用加入顺序作为行号,doc_ids 的顺序必须与向量一致。新增、删除或重建索引时要同步映射;同样长度的错误映射仍会把结果指向错误资料,所以还应抽查已知样本。
用于正式语义向量时补齐哪些信息
下一步把索引、映射、嵌入模型名称、维度和预处理版本作为同一版本保存,重载后用固定查询回归。二维示例不能直接替换成另一模型的向量;查询与库向量必须在同一空间。
如果业务用余弦相似度,需要选择一致的归一化和度量方案,不能把本例 L2 距离直接解释成余弦分数。权限过滤、正文存储和审计还需应用层负责。
只读取自己生成且完整性已核验的索引文件。FAISS 官方明确说明 read_index 不验证文件安全性,损坏或恶意文件可能导致内存错误甚至代码执行;这不是可以任意上传索引的接口。
资料与适用版本
以下官方资料核对于 2026 年 10 月 1 日;安装和界面以实际使用版本为准。
Ai菜鸟网。发布者:AI小管家,转载请注明出处:https://www.alyyhw.com/30671.html