Skip to main content

zvec-db

Version Python 3.12+ License Documentation Tests

Sparse/dense vectorization and document reranking toolkit for zvec.

Requires: zvec >= 0.7.0

zvec-db provides:

  • 🚀 Hybrid search - Combine sparse (BM25) and dense (semantic) vectors with full-text search
  • 🔄 Score fusion - Weighted fusion and Reciprocal Rank Fusion (RRF)
  • 🎯 Cross-encoder reranking - Two-stage retrieval with local or API-based rerankers
  • 📦 6 sparse embedders - BM25, BM25L, BM25+, TF-IDF, Count, DisMax
  • 🔧 Score normalization - Bayesian, minmax, percentile, arctan, and auto modes (NormalizeMode)
  • ⚡ Native search dispatch - RRF fusion passed straight into the zvec C++ engine via search(), with zero Python-object conversion

Quick Start

pip install zvec-db

Complete Example: Hybrid Search with RerankPipeline

from zvec_db import search, RerankPipeline, ScoreNormalizer, WeightedReranker
from zvec_db.rerankers import SentenceTransformerReranker
from zvec_db.embedders import BM25Embedder, SentenceTransformersEmbedder
import zvec

# 1. Open collection and initialize embedders
collection = zvec.open("./my_collection")
bm25 = BM25Embedder(max_features=4096)
bm25.load("./bm25.joblib")
dense = SentenceTransformersEmbedder(model_name="all-MiniLM-L6-v2")

# 2. Create rerank pipeline with auto-detection from schema
reranker = RerankPipeline(
    normalizer=ScoreNormalizer(
        method="bayes",
        schema=collection.schema,  # Auto-detect metrics (COSINE, L2, IP)
    ),
    fusion=WeightedReranker(
        weights={"sparse": 0.5, "dense": 0.3, "text": 0.2},
        topk=16,  # Top 16 after fusion
    ),
    cross_encoder=SentenceTransformerReranker(
        model_name="cross-encoder/ms-marco-MiniLM-L-6-v2",
        topk=8,  # Top 8 after cross-encoder
    ),
)

# 3. Search with full pipeline
results = search(
    collection=collection,
    query="neural networks",
    sparse_fields={"sparse": bm25},
    dense_fields={"dense": dense},
    fts_fields="text",
    reranker=reranker,
    topk=32,  # Fetch 32 candidates
)

for doc in results:
    print(f"{doc.fields['text']} (score: {doc.score:.4f})")

Simple Search (No Reranking)

from zvec_db import search

results = search(
    collection=collection,
    query="neural networks",
    sparse_fields={"sparse": bm25},
    dense_fields={"dense": dense},
    topk=10,
)

Search with Filter

from zvec_db import search

# Filter with SQL-like WHERE clause
results = search(
    collection=collection,
    query="neural networks",
    sparse_fields={"sparse": bm25},
    dense_fields={"dense": dense},
    filter="publish_year >= 2020 AND category == 'research'",
    topk=10,
)

Custom Fusion Only

from zvec_db.rerankers import WeightedReranker

reranker = WeightedReranker(weights=[0.7, 0.3])

results = search(
    collection=collection,
    query="neural networks",
    sparse_fields={"sparse": bm25},
    dense_fields={"dense": dense},
    reranker=reranker,
)

Search with Minimum Score

from zvec_db import search

# Filter out results with score below 0.5
results = search(
    collection=collection,
    query="neural networks",
    sparse_fields={"sparse": bm25},
    dense_fields={"dense": dense},
    min_score=0.5,  # Only keep results with score >= 0.5
    topk=10,
)

Full-Text Search with the Native ngram Tokenizer

zvec ships native C++ tokenizers for its full-text search (FTS) indexes: standard (default), ngram, jieba, and whitespace. The ngram tokenizer indexes every substring of n characters, enabling partial-word and typo-tolerant matching (e.g. searching "vector" matches "vectors", "vectorize") and works on any language without a dictionary.

Configure it on the FTS field when creating the collection with FtsIndexParam:

import zvec

schema = zvec.CollectionSchema(
    name="my_collection",
    fields=[
        zvec.FieldSchema(
            name="text",
            data_type=zvec.DataType.STRING,
            index_param=zvec.FtsIndexParam(
                tokenizer_name="ngram",
                filters=["lowercase"],
                extra_params='{"ngram_min": 2, "ngram_max": 3, "token_chars": ["letter", "digit"]}',
            ),
        )
    ],
)
collection = zvec.create_and_open("./my_collection", schema)

Then search the field with fts_fields="text" as usual — the query is tokenized with the same ngram pipeline at query time:

results = search(
    collection=collection,
    query="vector",
    fts_fields="text",
    topk=10,
)

extra_params keys for the ngram tokenizer:

Key Values Default Description
ngram_min positive integer 2 Minimum n-gram length
ngram_max positive integer 2 Maximum n-gram length
token_chars array of "letter", "digit", "whitespace", "punctuation", "symbol" [] (all valid UTF-8 characters) Character classes kept for n-gram building

Note: Larger ngram_max values increase index size. For most use cases {"ngram_min": 2, "ngram_max": 3} is a good trade-off between recall and index footprint. The other native tokenizers (standard, jieba for Chinese, whitespace) accept their own extra_params — see the zvec FtsIndexParam documentation.


API Reference

search() Parameters

Parameter Type Description
collection zvec.Collection Collection to search
query str Query text
sparse_fields dict[str, Embedder] Sparse fields (e.g., {"sparse": bm25})
dense_fields dict[str, Embedder] Dense fields (e.g., {"dense": dense})
fts_fields str | list[str] FTS fields
reranker Reranker Reranker instance
topk int Number of candidates to fetch (before filtering)
min_score float Minimum score threshold (filter out low scores)
output_fields list[str] Fields to include in results
filter str Conditional filter (SQL-like WHERE clause)

Reranker Types

Type Description
WeightedReranker(weights={...}) Weighted fusion
RrfReranker() Reciprocal Rank Fusion
SentenceTransformerReranker() Cross-encoder (local, HuggingFace models)
OpenAIReranker(endpoint=...) Cross-encoder via OpenAI-compatible API (e.g., vLLM)
RerankPipeline(normalizer=..., fusion=..., cross_encoder=...) Full pipeline

Embedders

Sparse (lexical): BM25Embedder (recommended), BM25LEmbedder, BM25PlusEmbedder, TfidfEmbedder, CountEmbedder, DisMaxEmbedder

Dense (semantic): SentenceTransformersEmbedder, OpenAIEmbedder

from zvec_db import BM25Embedder, SentenceTransformersEmbedder

bm25 = BM25Embedder(max_features=4096)
bm25.load("./bm25.joblib")  # load() returns None, assign separately
dense = SentenceTransformersEmbedder(model_name="all-MiniLM-L6-v2")

bm25.save("bm25.joblib")

Rerankers

Fusion: WeightedReranker (weighted sum), RrfReranker (rank-based)

Cross-Encoder: SentenceTransformerReranker, OpenAIReranker

Pipeline: RerankPipeline (normalization + fusion + cross-encoder)

from zvec_db import RerankPipeline, ScoreNormalizer, WeightedReranker
from zvec_db.rerankers import SentenceTransformerReranker

# Full pipeline with schema auto-detection
pipeline = RerankPipeline(
    normalizer=ScoreNormalizer(method="bayes", schema=collection.schema),
    fusion=WeightedReranker(weights={"sparse": 0.7, "dense": 0.3}),
    cross_encoder=SentenceTransformerReranker(topk=10),
)

Performance tip: When you call search() with an RrfReranker, zvec-db passes it straight into the native C++ engine (collection.query), so RRF fusion runs natively with no Python-object conversion. WeightedReranker and in-process rerank() calls fuse in pure Python by design — benchmarking showed the per-document Python↔C++ conversion round trip costs more than native fusion saves at every scale (see benchmarks/README.md).


Documentation


License

MIT License

Metadata

Release files for zvec-db 0.19.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for zvec-db 0.19.0
File Size Uploaded Provenance Actions
zvec_db-0.19.0.tar.gz 154.9 kB Without provenance Details for zvec_db-0.19.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for zvec-db 0.19.0
File Interpreter ABI Platform Actions
zvec_db-0.19.0-py3-none-any.whl Python 3 none any Details for zvec_db-0.19.0-py3-none-any.whl

Total release size: 337.1 kB

Release files / zvec_db-0.19.0.tar.gz

Download URL zvec_db-0.19.0.tar.gz
Size 154.9 kB
Tags Source
SHA-256 checksum
How to use checksums
a58b60dfa5588f471e15564ad339f8e69598bc71b439d8760218a179dc21713f
BLAKE2b-256 checksum
How to use checksums
fa9b8ee30b43aad107adbd43e6f644c4f5874afcd1af02eb856c51eb1a3638a8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / zvec_db-0.19.0-py3-none-any.whl

Download URL zvec_db-0.19.0-py3-none-any.whl
Size 182.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
11de510f26439fee096c33ea95f9cd60d56636fb2b032bf470a49acffab2913f
BLAKE2b-256 checksum
How to use checksums
b5f3689c9548bf558aceb7220edfb5d8027f7cd2b932e5054101684c3a3b50a2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for zvec-db 0.19.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page