Sparse vector index
The sparse vector index (SparseVectorIndexConfig) strengthens keyword-oriented retrieval. Unlike dense vectors (for example BERT or OpenAI embeddings), which emphasize semantic similarity, sparse vectors (for example BM25 or SPLADE) emphasize exact keyword matching.
Use cases and benefits
- Exact keyword matching: For proper nouns, abbreviations, serial numbers, or domain terms, sparse vectors often match more accurately than dense vectors.
- Interpretability: Each dimension usually maps to a vocabulary token, so results are easier to explain.
- Out-of-domain generalization (Out-of-Domain): Without domain-tuned dense models, statistical sparse models such as BM25 are often more robust.
- Hybrid search: Combining dense vectors for semantics and sparse vectors for exact matching often improves recall at K (Recall@K).
Field reference
SparseVectorIndexConfig configures sparse vector indexes such as BM25 and SPLADE and supports hybrid retrieval with dense vectors. Fields:
| Field | Type | Default | Description and constraints | Required |
|---|---|---|---|---|
| embedding_function | SparseEmbeddingFunction | None | Must support persistence (name, get_config, build_from_config) | Yes |
| source_key | str | K | K.DOCUMENT | Data source for sparse vectors: #document or a metadata field name (such as "title") | No |
| lib | str | "vsag" | Only vsag is supported | No |
| distance | str | "inner_product" | Sparse vectors support inner_product only | No |
| type | str | "sindi" | Only sindi is supported | No |
| prune | bool | False | Whether pruning is enabled | No |
| refine | bool | False | Whether refine is enabled | No |
| drop_ratio_build | float | 0.0 | Ratio of small weights ignored at index build time (0.0–0.9) | No |
| drop_ratio_search | float | 0.0 | Ratio of small weights ignored at search time (0.0–0.9); larger values are faster but may reduce accuracy | No |
| refine_k | float | 4.0 | Rerank candidate multiplier (1.0–1000.0) | No |
| properties | dict | None | Keys and values must be primitive types | No |
Constraints and behavior:
- At most one sparse vector index per collection; sparse vectors are stored in the
sparse_embeddingcolumn. source_keyofK.DOCUMENTor"#document"means vectors are built from document content; a plain string means vectors are built frommetadata[source_key].resolve_source_key()returns("document", None)or("metadata", metadata_key)so internals or callers can tell where data came from.
Usage
To use a sparse vector index in pyseekdb, configure it through Schema when you create a collection.
Prerequisites
Install pyseekdb V1.2.0 or later.
pip install -U pyseekdb
For BM25, install the dependency.
pip install "bm25s[full]"
For SPLADE, install the dependency.
pip install sentence-transformers>=4.0
Usage examples
-
Configure a sparse vector index with the built-in BM25 algorithm
import pyseekdb
from pyseekdb import Client, Schema, SparseVectorIndexConfig, K
from pyseekdb.utils.embedding_functions import BM25SparseEmbeddingFunction
# 1. Initialize the client (embedded mode in this example)
client = Client()
# 2. Define schema
# BM25 sparse index, document content (K.DOCUMENT) as source
sparse_config = SparseVectorIndexConfig(
embedding_function=BM25SparseEmbeddingFunction(k=1.2, b=0.75),
source_key=K.DOCUMENT, # or a metadata field such as "title"
drop_ratio_search=0.2 # prune ratio at search time for speed
)
schema = Schema(
sparse_vector_index=sparse_config
)
# 3. Create collection
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. Add data
# pyseekdb generates sparse vectors with the configured BM25 function
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. Sparse vector query
# query_key=K.SPARSE_EMBEDDING selects the sparse index
results = collection.query(
query_texts=["machine learning"],
query_key=K.SPARSE_EMBEDDING,
n_results=2
)
print("Sparse Search Results:", results) -
Configure a sparse vector index with the built-in SPLADE algorithm
For deep-learning sparse vectors (such as SPLADE), use
HuggingFaceSparseEmbeddingFunction:from pyseekdb.utils.embedding_functions import HuggingFaceSparseEmbeddingFunction
splade_ef = HuggingFaceSparseEmbeddingFunction(
device="cpu"
)
config = SparseVectorIndexConfig(embedding_function=splade_ef) -
Dense and sparse hybrid search example
Hybrid search usually runs dense vector retrieval (semantic) and sparse vector retrieval (keywords) together, then merges results (for example with weighted sums or RRF reciprocal rank fusion).
The following end-to-end example merges candidates with a RERANKER model (
cross-encoder/ms-marco-MiniLM-L-6-v2).-
Install dependencies (pyseekdb and the SPLADE sparse model).
pip install pyseekdb sentence-transformers -
Dense and sparse hybrid search example:
# =====================================================================
# 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)")
# Possible sample output:
# 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.
-