You need to enable JavaScript to run this app. 如何保存使用ScaNN工具构建的向量检索索引?
优惠活动
大模型
产品
解决方案
定价
更多

如何保存使用ScaNN工具构建的向量检索索引?

你可以直接使用ScaNN内置的序列化接口完成索引的保存和加载,操作步骤如下:

保存索引

构建完searcher对象后,调用内置的serialize()方法将索引序列化为二进制流,写入本地文件即可,示例代码接你已有构建逻辑补充即可:

# 你已有的索引构建代码
start = time.time()
searcher = scann.scann_ops_pybind.builder(normalized_dataset, 10, "dot_product").tree(
    num_leaves=2000, num_leaves_to_search=100, training_sample_size=250000).score_ah(
    2, anisotropic_quantization_threshold=0.2).reorder(100).build()
end = time.time()
print("Index Latency (ms): {:8.4f}".format( 1000*(end - start)) )

# 新增索引保存逻辑
index_save_path = "./scann_index.bin"
with open(index_save_path, "wb") as f:
    f.write(searcher.serialize())

注意:ScaNN索引本身只存储检索需要的量化结构、树结构等信息,不会存储你传入的原始normalized_dataset向量,如果后续需要用到原始向量请单独备份存储。

加载已保存的索引

需要使用索引时不需要重新执行构建流程,直接调用load_searcher接口读取本地保存的索引文件即可:

import scann

index_save_path = "./scann_index.bin"
with open(index_save_path, "rb") as f:
    searcher = scann.scann_ops_pybind.load_searcher(f.read())

# 加载完成后可直接执行检索,示例如下
# neighbors, distances = searcher.search(query_vector, final_num_neighbors=10)

注意:保存的索引和加载时使用的ScaNN版本需要保持一致,避免出现版本不兼容导致的加载失败问题。

内容的提问来源于stack exchange,提问作者Ramraj Chandradevan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 06:18:03