稀疏向量索引
稀疏向量索引(SparseVectorIndexConfig)旨在增强基于关键词的检索能力。与传统的稠密向量(Dense Vector,如 BERT/OpenAI Embeddings)侧重于语义匹配不同,稀疏向量(Sparse Vector,如 BM25, SPLADE)更侧重于精确的关键词匹配。
使用场景与优势
- 精确关键词匹配: 对于专有名词、缩写、序列号或特定行业术语,稀疏向量往往能提供比稠密向量更准确的匹配结果。
- 可解释性强: 稀疏向量的每一维通常对应词表中的一个 Token,检索结果更容易解释。
- 域外泛化性 (Out-of-Domain): 在没有针对特定领域微调稠密模型的情况下,基于统计的稀疏模型(如 BM25)通常表现更稳健。
- 混合搜索 (Hybrid Search): 结合稠密向量的语义理解能力和稀疏向量的精确匹配能力,通常能显著提升检索召回率 (Recall@K)。
字段说明
SparseVectorIndexConfig 用于 BM25、SPLADE 等稀疏向量索引,支持与稠密向量做混合检索。其涉及的字段说明如下:
| 字段 | 类型 | 默认值 | 说明与约束 | 是否必填 |
|---|---|---|---|---|
| embedding_function | SparseEmbeddingFunction | 无 | 须支持持久化(name、get_config、build_from_config) | 是 |
| source_key | str | K | K.DOCUMENT | 指定生成稀疏向量的数据源。数据来源:#document 或 metadata 字段名(如 "title") | 否 |
| lib | str | "vsag" | 当前仅支持 vsag | 否 |
| distance | str | "inner_product" | 稀疏向量仅支持 inner_product | 否 |
| type | str | "sindi" | 当前仅支持 sindi | 否 |
| prune | bool | False | 是否启用剪枝 | 否 |
| refine | bool | False | 是否启用 refine | 否 |
| drop_ratio_build | float | 0.0 | 构建索引时忽略小权重的比例 (0.0 - 0.9) | 否 |
| drop_ratio_search | float | 0.0 | 搜索时忽略小权重的比例 (0.0 - 0.9),值越大搜索越快但精度可能下降 | 否 |
| refine_k | float | 4.0 | 重排序候选集倍数 (1.0 - 1000.0) | 否 |
| properties | dict | 无 | 键值须为原始类型 | 否 |
约束与行为:
- 每个集合最多支持配置一个稀疏向量索引;稀疏向量写入
sparse_embedding列。 source_key为K.DOCUMENT或"#document"表示从文档内容生成;普通字符串表示从metadata[source_key]生成。resolve_source_key()返回 ("document", None) 或 ("metadata", metadata_key),便于内部或调用方区分数据来源。
使用方法
要在 pyseekdb 中使用稀疏向量索引,您需要在创建集合时通过 Schema 进行配置。
前置条件
确保已安装 pyseekdb V1.2.0 或更高版本。
pip install -U pyseekdb
如果使用 BM25,需要安装依赖。
pip install "bm25s[full]"
如果使用 SPLADE,需要安装依赖
pip install sentence-transformers>=4.0
使用示例
-
使用内置的 BM25 算法配置稀疏向量索引
import pyseekdb
from pyseekdb import Client, Schema, SparseVectorIndexConfig, K
from pyseekdb.utils.embedding_functions import BM25SparseEmbeddingFunction
# 1. 初始化客户端 (这里使用 Embedded 模式)
client = Client()
# 2. 定义 Schema
# 配置 BM25 稀疏向量索引,使用文档内容 (K.DOCUMENT) 作为来源
sparse_config = SparseVectorIndexConfig(
embedding_function=BM25SparseEmbeddingFunction(k=1.2, b=0.75),
source_key=K.DOCUMENT, # 也可以指定 metadata 字段,如 "title"
drop_ratio_search=0.2 # 搜索时的剪枝比例,用于加速
)
schema = Schema(
sparse_vector_index=sparse_config
)
# 3. 创建集合
collection_name = "demo_sparse_collection"
if collection_name in client.list_collections():
client.delete_collection(collection_name)
collection = client.create_collection(
name=collection_name,
schema=schema
)
# 4. 添加数据
# pyseekdb 会自动使用配置的 BM25 函数生成稀疏向量
collection.add(
ids=["1", "2", "3"],
documents=[
"Machine learning is fascinating.",
"Python is a great programming language.",
"Artificial Intelligence and machine learning are related."
]
)
# 5. 执行稀疏向量检索
# 使用 query_key=K.SPARSE_EMBEDDING 指定使用稀疏索引
results = collection.query(
query_texts=["machine learning"],
query_key=K.SPARSE_EMBEDDING,
n_results=2
)
print("Sparse Search Results:", results) -
使用内置的 SPLADE 算法配置稀疏向量索引
如果您希望使用深度学习模型生成的稀疏向量(如 SPLADE),可以使用
HuggingFaceSparseEmbeddingFunction:from pyseekdb.utils.embedding_functions import HuggingFaceSparseEmbeddingFunction
splade_ef = HuggingFaceSparseEmbeddingFunction(
device="cpu"
)
config = SparseVectorIndexConfig(embedding_function=splade_ef) -
稠密与稀疏向量混搜示例
混合搜索通常指同时执行稠密向量检索(语义)和稀疏向量检索(关键词),然后通过算法(如加权求和或 RRF 倒数排名融合)合并结果。
以下是一个完整的混合搜索实现示例,使用了 RERANKER 模型(cross-encoder/ms-marco-MiniLM-L-6-v2)来合并结果。
-
安装依赖环境(pyseekdb 和 splade 稀疏模型)。
pip install pyseekdb sentence-transformers -
稠密与稀疏向量混搜示例如下所示。
# =====================================================================
# Hybrid search with pluggable reranking strategies
# Install denpendencies first:
# pip install pyseekdb sentence-transformers
# =====================================================================
import pyseekdb
from pyseekdb import Client, Schema, SparseVectorIndexConfig, HNSWConfiguration, K
from pyseekdb.utils.embedding_functions import HuggingFaceSparseEmbeddingFunction
from typing import Any
def _rerank_model(
query_text: str,
candidate_ids: list[str],
candidate_docs: dict[str, str],
model_name: str,
) -> dict[str, float]:
"""
Cross-encoder reranking: score every (query, document) pair with a
cross-encoder model and return the relevance scores.
Requires: ``pip install sentence-transformers``
"""
from sentence_transformers import CrossEncoder
model = CrossEncoder(model_name)
pairs = [(query_text, candidate_docs[doc_id]) for doc_id in candidate_ids]
raw_scores: list[float] = model.predict(pairs).tolist()
return dict(zip(candidate_ids, raw_scores, strict=True))
def perform_hybrid_search(
collection,
query_text: str,
top_k: int = 5,
*,
rrf_k: int = 60,
rerank_model: str = "cross-encoder/ms-marco-MiniLM-L-6-v2",
) -> dict[str, Any]:
"""
Hybrid search combining dense and sparse retrieval with pluggable reranking.
Args:
collection: pyseekdb collection (must have both dense and sparse indexes).
query_text: The query string.
top_k: Number of final results to return.
rerank_model: HuggingFace cross-encoder model name (only used when
``rerank="model"``).
Returns:
``{"ids": [...], "documents": [...], "scores": [...]}``
"""
# 1. Retrieve candidates from both indexes
dense_results = collection.query(query_texts=[query_text], n_results=top_k)
sparse_results = collection.query(
query_texts=[query_text],
query_key=K.SPARSE_EMBEDDING,
n_results=top_k,
)
dense_ids: list[str] = dense_results["ids"][0] if dense_results["ids"] else []
sparse_ids: list[str] = sparse_results["ids"][0] if sparse_results["ids"] else []
# 2. Rerank
all_ids = list(dict.fromkeys(dense_ids + sparse_ids))
if not all_ids:
return {"ids": [], "documents": [], "scores": []}
fetched = collection.get(ids=all_ids)
id_to_doc = dict(zip(fetched["ids"], fetched["documents"], strict=True))
scores = _rerank_model(query_text, all_ids, id_to_doc, rerank_model)
# 3. Sort by score descending, take top_k
sorted_ids = sorted(scores, key=scores.get, reverse=True)[:top_k]
if not sorted_ids:
return {"ids": [], "documents": [], "scores": []}
# 4. Fetch documents in final order
fetched = collection.get(ids=sorted_ids)
id_to_doc = dict(zip(fetched["ids"], fetched["documents"], strict=True))
return {
"ids": sorted_ids,
"documents": [id_to_doc.get(sid, "") for sid in sorted_ids],
"scores": [round(scores[sid], 6) for sid in sorted_ids],
}
# =====================================================================
# Demo: hybrid search with all three reranking strategies
# =====================================================================
hybrid_collection_name = "hybrid_demo"
client = Client()
schema = Schema(
vector_index=HNSWConfiguration(dimension=384),
sparse_vector_index=SparseVectorIndexConfig(
embedding_function=HuggingFaceSparseEmbeddingFunction(),
source_key=K.DOCUMENT,
),
)
collection = client.create_collection(hybrid_collection_name, schema=schema)
docs = [
"Apple uses advanced chips in iPhones.",
"Apples are red and delicious fruits.",
"Oranges are rich in Vitamin C.",
"Apple pie is a popular dessert.",
"The tech giant Apple released a new laptop.",
]
ids = [str(i) for i in range(len(docs))]
collection.add(documents=docs, ids=ids)
query = "apple fruit"
# --- Cross-encoder reranker (requires sentence-transformers) ---
try:
print(f"\n=== Query: '{query}' | rerank='model' ===")
results = perform_hybrid_search(collection, query)
for i, doc_id in enumerate(results["ids"]):
print(f" {i + 1}. ID={doc_id} score={results['scores'][i]:.6f} | {results['documents'][i]}")
except ImportError:
print("\n(install sentence-transformers to enable: `pip install sentence-transformers)")
# 可能的输出结果:
# 1. ID=1 score=5.194160 | Apples are red and delicious fruits.
# 2. ID=3 score=-5.246192 | Apple pie is a popular dessert.
# 3. ID=4 score=-9.493382 | The tech giant Apple released a new laptop.
# 4. ID=0 score=-9.543316 | Apple uses advanced chips in iPhones.
# 5. ID=2 score=-10.001063 | Oranges are rich in Vitamin C.
-