蓝色天空网mbsky.com · 知识 · 实践 · 创造AI(人工智能) · 本地阅读预览
教程 / AI / 智能开发 / AI(人工智能)

向量数据库,从精确基线到混合检索

用实际 Faiss、Chroma 和 Qdrant 本地实例比较距离、索引、过滤与重载。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

先固定向量空间和精确基线

向量是编码器对文本、图像或其他对象的数值表示。向量库可把向量、稳定 ID、原文定位和元数据关联起来。小规模 RAG 可以直接计算距离,数据与请求量增长时再评估索引和服务。记录嵌入模型版本、输入用途、维度和距离定义,更新编码器时重新验证索引兼容性。

精确 top-k 会为每个候选计算距离或相似度。对 N 条 d 维稠密向量,逐条距离计算约为 O(Nd),完整排序另有开销,可改用部分选择。运行时间受硬件、批次、布局、线程和缓存影响。将同条件的精确结果作为近似索引的基线,记录并列分数的处理。

L2 距离越小越近,平方 L2 保持同一排序。Faiss 的 L2 索引返回平方距离。内积通常按大值优先,向量长度会影响分数。余弦衡量方向,对零向量无定义。双方做单位范数归一化后,余弦等于内积,平方 L2 等于 2−2×余弦。本站用小向量验证三种排序、归一化和零向量异常。

比较 HNSW、IVF 和乘积量化

HNSW 上层较稀疏,底层包含所有节点。查询先经上层缩小范围,再在底层沿邻接关系扩展候选,仍可能错过最近邻。M 控制连接数参数,efConstruction 与 efSearch 影响建图和检索时的候选范围。固定数据与距离,改变 efSearch 后比较召回和成本。

IVF 先训练粗聚类中心,再把向量分配到对应倒排列表。nlist 决定列表数,nprobe 决定查询探测列表数。本站在 Faiss 训练并构建四个列表,对照只探测最近列表与探测全部列表,同时用 NumPy 复算候选内的精确排名。另用 4.99 的边界查询比较两个列表。只探测一桶得到编号 1,探测两桶找回平方距离更小的编号 2。图中给出实际结果。

Faiss 探测一桶得到编号 1,探测两桶找回编号 2 的最近邻
本站实测边界查询 4.99。候选范围改变了最近邻,结果使用平方 L2。

PQ 把向量分成多个子向量,每段独立用码本表示。128 维向量分成 8 段、每段 256 个中心时,每个编码理想占 8 字节,原始 FP32 向量是 512 字节。实际索引还保存中心、ID、表和配置。IVF‑PQ 组合粗筛与压缩,距离可以是近似值,即使探测全部列表也应继续核对召回。本站运行真实压缩索引并检查码长与查询。

通过库或服务持久化

Faiss 是索引库。Flat 作为基线,IVF 和 PQ 需要训练代表性样本。训练完成后添加向量并搜索。保存的索引需与文档和 ID 的映射一同保管。本站用可信自建文件实际写入、重开,再增量加入一条向量并确认旧索引不变。

Chroma 的持久化客户端可显式接收向量。提供固定向量时关闭自动嵌入并保持集合维度一致。本站实际批量写入,按元数据筛选,修改和删除部分记录,再在另一 Python 进程重开同一目录检查结果。

Qdrant 客户端可连接独立服务,也可使用路径启动本地模式。先建立有固定维度和度量的集合,再 upsert 带 payload 的点,用 query_points 和 query_filter 检索。本站关闭并重开本地目录核对更新后的排序。服务端分片、网络与权限需要独立验证。

选择编码器并评测检索组合

先按语言、任务、输入长度、许可与运行方式选嵌入模型。文档与查询应使用匹配的模型和输入配置。向量维度增加会提高原始存储和距离计算开销,效果需要测试集衡量。表中的默认维度仅用于型号识别,API 的可选维度和账单以提供方文档及当前配置为准。

BM25 结合词频、文档频率和长度归一化。先核对分词,连续中文可能被通用正则当作一个词。本站用明确分词测算 BM25,并验证无关文档分数为零。向量结果和关键词结果可按 ID 做倒数排名融合。每路名次从 1 起算,跨路出现时累加,固定同分顺序。加权分数融合先校准分数尺度,再按验证集选权重。

重排只对召回的候选计算查询与文档的联合分数。Bi‑Encoder 允许预先编码文档,Cross‑Encoder 对每个候选联合编码。后者能否提升质量与候选数、模型和任务有关。本站另用可解释的词项与短语规则实际改变候选顺序,真实神经重排模型、远程 API 及其质量与成本待实测。

把过滤、更新与监测纳入合同

预过滤先决定哪些记录有资格竞争 top-k。全局 top-k 后再筛选可能漏掉有资格但原本排名较低的记录。过滤语义需用具体后端验证,区分业务权限、元数据限制和候选窗口。本站用同一向量集实测了两个顺序的差异。

按 ID 分片便于定位记录,但全局搜索可能需要向多个分片扇出并合并。按聚类选择部分分片可减少候选,也会影响召回。记录批量更新、删除、模型及索引版本。索引训练数据分布变化时评估重建;保留上一版本用于回退。监控 P50、P95、P99 延迟、QPS、磁盘与内存、过滤后命中及相对精确基线的 Recall@k。

稠密向量的规模与理论原始存储

数量逐条扫描128 维 FP32 数据量
1 万逐条比较一万个向量。5.12 MB,实际时延另测。
100 万逐条比较一百万个向量。512 MB,仍须按批次与硬件测量。
1000 万逐条比较一千万个向量。5.12 GB,不含索引元数据。
1 亿逐条比较一亿个向量。51.2 GB,评估缓存、分片或压缩。
10 亿逐条比较十亿个向量。512 GB,按召回、延迟和总容量选择方案。

索引方法与适用条件

方法搜索方式需核对的差异
暴力搜索计算所有候选距离。同数据和度量下作为精确基线。
HNSW多层邻接图及候选扩展。查询和建图参数影响内存、延迟与召回。
IVF训练中心并探测部分列表。探测范围改变候选。
IVF-PQ先粗筛,再用码本近似距离。测量编码大小、距离误差和召回。

度量方向与范围

度量含义实现条件
余弦相似度非零向量夹角,理论值在 −1 到 1。相似度大者优先,某些库返回 1−余弦。
L2 距离非负,越小越近。明确读取欧氏距离或平方欧氏距离。
内积分数受方向和范数影响。单位化后与余弦相同。

本地库与向量服务

产品部署形式选择与验证
FAISS本地索引库。应用负责权限、元数据与索引文件管理。
Chroma本地持久化或客户端连接服务。先固定度量与嵌入输入,再实测过滤。
Qdrant独立服务或客户端本地模式。固定向量集合、payload 和查询版本。
Milvus向量数据库,可按部署模式运行。核对当前部署规模、索引与更新合同。
Weaviate可自管或使用托管服务。选择向量来源、检索模块与租户隔离。
Pinecone托管向量服务。核对区域、容量、服务条款和费用。

嵌入型号的默认或典型维度

型号维度运行条件
OpenAI text-embedding-3-small1536API 默认维度,可按支持的配置缩短。
OpenAI text-embedding-3-large3072API 默认维度,可按支持的配置缩短。
Cohere Embed v3英文与多语文本 v3 常见为 1024明确型号与 query/document 输入类型。
bge-large-zh-v1.51024按官方模型卡确认查询指令与许可。
bge-m3稠密向量 1024稠密、稀疏和多向量输出的检索合同各异。
gte-largethenlper/gte-large 为 1024明确发布者及训练语言,避免混用同名变体。

检索方案对照

方案组成评估重点
纯向量搜索单路向量候选。比较召回、延迟和领域分布。
混合搜索关键词与向量候选融合。验证分词、ID 去重、覆盖和同分规则。
向量 + 重排向量召回后再算联合分数。观察候选漏召、重排数量和精度。
混合 + 重排融合后对有限候选重排。分别报告召回、重排收益与实际开销。

本机索引、度量和持久化对照

python · 阅读源码

"""Run native Faiss indexes and local Qdrant with original vector fixtures."""
from contextlib import closing
import socket
from importlib.metadata import version
from unittest.mock import patch

import faiss
import numpy as np
from qdrant_client import QdrantClient, models

from lab_tools import run_exercise


def recall_at_k(approximate, reference):
    return sum(len(set(result) & set(expected)) for result, expected in zip(approximate, reference, strict=True)) / reference.size


def native_faiss(checks, workspace):
    faiss.omp_set_num_threads(1)
    metric_demo = faiss.IndexFlatL2(2)
    metric_demo.add(np.array([[1,0],[1,2]],dtype="float32"))
    distances, ids = metric_demo.search(np.array([[1,0]],dtype="float32"),2)
    checks.expect("vector_db_faiss_squared", [[1,0],[1,2]], "Compare native L2 index IDs and squared distances",
                  [[[0,1]],[[0.,4.]]],[ids.tolist(),distances.tolist()])

    rng = np.random.default_rng(17)
    centers = np.eye(4,8,dtype="float32")*6
    vectors = np.concatenate([center + rng.normal(0,1,(96,8)) for center in centers]).astype("float32")
    queries = vectors[[3,97,200,300]].copy()
    flat = faiss.IndexFlatL2(8)
    flat.add(vectors)
    _, baseline = flat.search(queries,5)
    expected_ids = [3,97,200,300]
    checks.expect("vector_db_faiss_flat", expected_ids, "Search four inserted vectors against all 384 points",
                  [expected_ids,384],[baseline[:,0].tolist(),flat.ntotal])

    ivf = faiss.IndexIVFFlat(faiss.IndexFlatL2(8),8,4,faiss.METRIC_L2)
    ivf.train(vectors)
    ivf.add(vectors)
    ivf.nprobe = 1
    _, nearest = ivf.quantizer.search(queries,1)
    narrow_candidates = [ivf.invlists.list_size(int(row[0])) for row in nearest]
    _, narrow = ivf.search(queries,5)
    assignments = ivf.quantizer.assign(vectors,1).ravel()
    candidate_rankings = []
    for query,bucket in zip(queries,nearest.ravel(),strict=True):
        candidate_ids = np.flatnonzero(assignments==bucket)
        squared = ((vectors[candidate_ids]-query)**2).sum(axis=1)
        candidate_rankings.append(candidate_ids[np.argsort(squared)[:5]])
    ivf.nprobe = 4
    distances, wide = ivf.search(queries,5)
    checks.expect("vector_db_faiss_ivf",[1,4,4],"Train centroids, compare candidate sizes and search all lists against exact ranking",
                  [True,True,1.0,expected_ids,True],
                  [ivf.is_trained,all(0<n<flat.ntotal for n in narrow_candidates),
                   recall_at_k(wide,baseline),wide[:,0].tolist(),np.array_equal(narrow,candidate_rankings)])
    checks.expect("vector_db_faiss_ivf_recall",[1,4],"Measure top-five recall on four queries against exact ranking",
                  [recall_at_k(candidate_rankings,baseline),1.0],
                  [recall_at_k(narrow,baseline),recall_at_k(wide,baseline)])
    checks.expect("vector_db_faiss_ivf_lists",4,"Count native inverted-list entries after training and adding",
                  384,sum(ivf.invlists.list_size(i) for i in range(ivf.nlist)))

    boundary = faiss.IndexIVFFlat(faiss.IndexFlatL2(1),1,2,faiss.METRIC_L2)
    boundary.train(np.repeat(np.array([[0.],[10.]],dtype="float32"),80,axis=0))
    boundary.add(np.array([[0.],[4.5],[5.1],[10.]],dtype="float32"))
    boundary_query = np.array([[4.99]],dtype="float32")
    observed = []
    for probes in (1,2):
        boundary.nprobe = probes
        values, found = boundary.search(boundary_query,1)
        observed.append([int(found[0,0]),round(float(values[0,0]),6)])
    checks.expect("vector_db_ivf_boundary", [4.99,[1,2]],
                  "Query near the boundary and recover the exact nearest point by probing both lists",
                  [[1,0.2401],[2,0.0121]],observed)

    graph = faiss.IndexHNSWFlat(8,8)
    graph.hnsw.efConstruction = 40
    graph.add(vectors)
    graph.hnsw.efSearch = 8
    _, low = graph.search(queries,5)
    graph.hnsw.efSearch = 64
    _, high = graph.search(queries,5)
    checks.expect("vector_db_faiss_hnsw", [8,40,[8,64]], "Build a native graph and compare searches to the same exact index",
                  [expected_ids,expected_ids,True,True],
                  [low[:,0].tolist(),high[:,0].tolist(),
                   recall_at_k(low,baseline)>=0.8,recall_at_k(high,baseline)>=0.95])

    pq = faiss.IndexIVFPQ(faiss.IndexFlatL2(8),8,4,2,2)
    pq.train(vectors)
    pq.add(vectors)
    pq.nprobe = 4
    pq_distances,pq_ids = pq.search(queries,5)
    checks.expect("vector_db_faiss_pq", [8,2,2], "Train compressed index and observe bytes per code and finite approximate distances",
                  [True,1,[4,5],True,True],
                  [pq.is_trained,pq.code_size,list(pq_ids.shape),bool(np.isfinite(pq_distances).all()),
                   not np.allclose(pq_distances,distances)])
    index_file = workspace/"ivf.bin"
    faiss.write_index(ivf,str(index_file))
    restored = faiss.read_index(str(index_file))
    restored.nprobe=4
    reopened_distances,reopened_ids=restored.search(queries,5)
    restored.add(np.array([[22]*8],dtype="float32"))
    _, added_ids = restored.search(np.array([[22]*8],dtype="float32"),1)
    checks.expect("vector_db_faiss_reload",index_file.name,"Write, reopen and append one vector without changing the original index",
                  [True,True,384,385,[[384]]],
                  [np.array_equal(reopened_ids,wide),np.allclose(reopened_distances,distances),ivf.ntotal,
                   restored.ntotal,added_ids.tolist()])


def qdrant_local(checks, workspace):
    directory=workspace/"qdrant"
    collection="inspection"
    with closing(QdrantClient(path=str(directory))) as client:
        client.create_collection(collection_name=collection,vectors_config=models.VectorParams(size=2,distance=models.Distance.COSINE))
        rows=[(10,[1.,0.],"staff"),(20,[0.8,0.6],"public"),(30,[0.,1.],"public")]
        client.upsert(collection,points=[models.PointStruct(id=i,vector=v,payload={"group":g}) for i,v,g in rows],wait=True)
        filtered=models.Filter(must=[models.FieldCondition(key="group",match=models.MatchValue(value="public"))])
        result=client.query_points(collection,query=[1.,0.],query_filter=filtered,limit=2,with_payload=True).points
        checks.expect("vector_db_qdrant_filter", [1.,0.], "Upsert local points and retrieve only eligible payloads",
                      [[20,30],[0.8,0.],["public","public"]],
                      [[r.id for r in result],[round(r.score,6) for r in result],[r.payload["group"] for r in result]])
        client.upsert(collection,points=[models.PointStruct(id=30,vector=[1.,0.],payload={"group":"public"})],wait=True)
    with closing(QdrantClient(path=str(directory))) as client:
        result=client.query_points(collection,query=[1.,0.],query_filter=filtered,limit=2).points
        checks.expect("vector_db_qdrant_reopen", "closed local client", "Reopen the path and inspect updated ranking and row count",
                      [[30,20],3], [[r.id for r in result],client.count(collection,exact=True).count])


def forbid_network(*_args,**_kwargs):
    raise AssertionError("these index fixtures use only local files")


def exercise(checks,workspace):
    names=["faiss-cpu","qdrant-client","numpy"]
    installed=[version(name) for name in names]
    checks.expect("vector_db_native_versions", names,"Read versions from installed package metadata",
                  ["1.16.0","1.20.0","2.5.4"],installed)
    sizes = [10_000,1_000_000,10_000_000,100_000_000,1_000_000_000]
    checks.expect("vector_db_raw_budget", [sizes,128,4], "Calculate raw FP32 bytes without the index",
                  [5120000,512000000,5120000000,51200000000,512000000000],[n*128*4 for n in sizes])
    query = "水泵 维保"
    candidates = [("log","维修 水泵"),("manual","水泵 维保 手册"),("form","水泵 维保 维保 表单")]
    def score(text):
        return len(set(query.split()) & set(text.split())) + (2 if query in text else 0)
    reordered = sorted(candidates,key=lambda row:(-score(row[1]),row[0]))
    checks.expect("vector_db_candidate_rerank", [query,candidates],
                  "Rescore only the candidate documents by term overlap and phrase match",
                  [["form",4],["manual",4],["log",1]],[[name,score(text)] for name,text in reordered])
    native_faiss(checks,workspace)
    with patch.object(socket.socket,"connect",forbid_network),patch.object(socket.socket,"connect_ex",forbid_network):
        qdrant_local(checks,workspace)


if __name__=="__main__":
    run_exercise(exercise)
预期结果 · 待实际运行核验
  • Faiss 探测全部倒排列表得到与精确索引相同的排名。Qdrant 本地过滤及重载遵循记录的结果。Chroma 可重开目录并查询已更新的记录。
本机索引、度量和持久化对照

所需环境:CPython 3.12.14、NumPy 2.5.4、Faiss 1.16.0、Chroma 1.5.9、Qdrant Client 1.20.0。CPU、本机文件及自编向量。

当前源码 SHA256:fffd6919e136fab2e1c59d25eb87c111e0ea15251cc3353c819f595f785da516

向量数据库练习 ZIP

含排序、Faiss、Qdrant 与 Chroma 可运行实例,以及本站观察页。

下载本站向量数据库练习

所需环境:CPython 3.12.14、NumPy 2.5.4、Faiss 1.16.0、Chroma 1.5.9、Qdrant Client 1.20.0。CPU、本机文件及自编向量。

ZIP SHA256:acb422fbcdfcba0d991797ba952b41607f4711cdfaa522217d266e93ae458b3b

常见错误与边界

  • 同样的度量名称可能对应不同分数方向和表示。
  • 全局 top-k 后再过滤可能丢掉符合条件的记录。

练习与解答

运行 index_lab.py,分别比较 nprobe 取 1 与 4、Qdrant 更新前后的候选。

展开参考解答

多列表扩大候选范围。重开 Qdrant 后,更新的编号 30 排在编号 20 前。

规范与官方依据