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,
)

Pass a list of query strings to run one full pipeline per query (embedding, per-source search, reranking) in parallel on a thread pool — latency stays close to the slowest single query instead of the sum:

results = search(
    collection=collection,
    query=["neural networks", "deep learning architectures"],
    sparse_fields={"sparse": bm25},
    dense_fields={"dense": dense},
    topk=10,
    max_workers=4,  # optional; None uses the ThreadPoolExecutor default
)

Two result behaviors via merge:

merge=True (default, fused) merge=False (independent)
Result budget max topk results total max topk results per query (up to topk × len(queries))
Combination one entry per document, best score across queries kept, sorted by score descending per-query lists concatenated in query order, no global sort (raw scores are not comparable across queries)
Dedup always dedup=True (default): keep only the first occurrence of a document; dedup=False: one entry per query
# Independent mode: each query keeps its own topk-bounded results
results = search(
    collection=collection,
    query=["neural networks", "deep learning architectures"],
    sparse_fields={"sparse": bm25},
    dense_fields={"dense": dense},
    topk=10,
    merge=False,
)

Notes: embedders and the collection must tolerate concurrent calls (the zvec C++ query and HTTP/GPU-bound embedders do); on failure, the first exception in query order propagates and no partial result is returned; raw scores are on incomparable scales across queries, so a fusion reranker is recommended for meaningful cross-query rankings.

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 | list[str] Query text, or a list of query texts for multi-query search (run in parallel)
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 (applied per query in multi-query mode)
topk int Number of candidates to fetch (before filtering); bounds the final result count when merge=True, the per-query count when merge=False
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)
max_workers int | None Max threads for multi-query search (None = ThreadPoolExecutor default); ignored for a single query
merge bool Multi-query mode: True (default) fuses results into one topk-bounded ranking; False returns per-query results concatenated (see "Multi-Query Search")
dedup bool With merge=False: keep only the first occurrence of documents found by several queries (default True); ignored otherwise

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.20.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.20.0
File Size Uploaded Provenance Actions
zvec_db-0.20.0.tar.gz 159.1 kB Without provenance Details for zvec_db-0.20.0.tar.gz

Built distribution (wheel)

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

Total release size: 345.0 kB

Release files / zvec_db-0.20.0.tar.gz

Download URL zvec_db-0.20.0.tar.gz
Size 159.1 kB
Tags Source
SHA-256 checksum
How to use checksums
07a16126b89423d1118ac2f694dfcaafee6fa6cffb0e84de02d14a66b1ab7aa0
BLAKE2b-256 checksum
How to use checksums
8ab0d0d7a4ceb23046c1a14a990a6e27c57de9f746940b408ea38ac5d4049556
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.20.0-py3-none-any.whl

Download URL zvec_db-0.20.0-py3-none-any.whl
Size 185.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
be44dec2aa81bafe9e39d4355dc9cfc3d6b25b1b3504d3149cd1efcf561ae2bc
BLAKE2b-256 checksum
How to use checksums
63739634659ff77d7295f2d42767266088f933c52be3ea2ac1bc3bcc733acee2
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.20.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