首页/AI/RAG 与向量库速查/FAISS 索引读写与合并
本包目录(229 条)
架构与流程30 条解析与切分33 条Embedding 与检索50 条
向量数据库49 条
重排与生成32 条评估与优化35 条

FAISS 索引读写与合并

FAISS 提供 write_index / read_index 做持久化,也可用 IndexIDMap 保存业务 id;多份索引可 merge_from 合并,适合分片构建再汇总的离线流水线。

RAG 与向量库速查AI更新于 2026-10-12

IndexIDMap 与合并

IndexIDMap 与合并
import faiss, numpy as np

idx = faiss.IndexFlatIP(384)
idmap = faiss.IndexIDMap(idx)
ids = np.arange(1000, 1010, dtype="int64")
idmap.add_with_ids(np.random.rand(10, 384).astype("float32"), ids)
faiss.write_index(idmap, "part.faiss")

p2 = faiss.read_index("part.faiss")
p1 = faiss.read_index("part_a.faiss")
p1.merge_from(p2)                      # 同类型索引可合并
faiss.write_index(p1, "merged.faiss")
用 add_with_ids 后检索返回业务 id,去掉额外维护的序号到 id 映射表。

易错点

  • 合并不同度量或不同维度的索引,构造上就不成立
  • 业务 id 用 int64 以外类型存储,转换期间溢出或丢精度

数据来源与参考

  • FAISS wiki(IndexIDMap / merge_from)
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌