Dev.to AI 🤖 Ai 👁 0 📖 4 min read

Qdrant Hybrid Search in Python: Dense Vectors + Sparse BM25 With RRF (0.942 vs 0.618 Recall)

Pure dense vector search is great at conceptual questions — and surprisingly bad at exact technical strings. Search your RAG docs for HTTP 504 DEADLINE_EXCEEDED or pg_stat_statements, and a dense embedding model often re

Pure dense vector search is great at conceptual questions — and surprisingly bad at exact technical strings. Search your RAG docs for HTTP 504 DEADLINE_EXCEEDED or pg_stat_statements, and a dense embedding model often returns generic timeout guides instead of the exact page containing that symbol.

Qdrant lets you store both dense semantic vectors and sparse lexical vectors (BM25 / SPLADE) in a single collection and fuse them server-side with Reciprocal Rank Fusion (RRF) — no second Elasticsearch cluster required.

TL;DR

  • Across 300 technical queries on 10,000 engineering docs, pure dense hit only 0.618 exact-keyword recall, while Hybrid RRF (dense + sparse) jumped to 0.942 exact-keyword recall and 0.928 conceptual recall at 3.7 ms mean latency.
  • Generate both dense and sparse vectors locally on CPU with fastembed.
  • Always put metadata Filter objects inside each Prefetch, not only at the outer query level, or security/tenant filters will starve your RRF fusion pool.

1. Create a Dual-Vector Collection in Qdrant

Qdrant's named vectors let one document hold both a dense embedding (text-dense) and a sparse inverted-index vector (text-sparse) next to the same payload:

from qdrant_client import QdrantClient, models

client = QdrantClient(location=":memory:")  # swap for url="http://localhost:6333" in prod
COLLECTION_NAME = "hybrid_docs"

client.create_collection(
    collection_name=COLLECTION_NAME,
    vectors_config={
        "text-dense": models.VectorParams(
            size=384,  # 384 for MiniLM, 1536 for text-embedding-3-small
            distance=models.Distance.COSINE,
        )
    },
    sparse_vectors_config={
        "text-sparse": models.SparseVectorParams(
            index=models.SparseIndexParams(on_disk=False)
        )
    },
)

(If you are choosing between cosine, dot product, and L2 for your dense space, see this benchmark on cosine vs dot product vs L2 vector search.)

2. Generate Dense + Sparse Vectors Locally With FastEmbed

Instead of paying external API fees for indexing or hand-rolling BM25 tokenizers, fastembed runs ONNX models locally on CPU to produce both vectors in one ingestion pass:

from fastembed import TextEmbedding, SparseTextEmbedding

dense_model = TextEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
sparse_model = SparseTextEmbedding(model_name="prithivida/Splade_PP_en_v1")

documents = [
    "PostgreSQL slow query logs and pg_stat_statements setup guide",
    "FastAPI async worker timeouts under high concurrency",
]

dense_vectors = list(dense_model.embed(documents))
sparse_vectors = list(sparse_model.embed(documents))

points = [
    models.PointStruct(
        id=idx,
        payload={
            "text": doc,
            "category": "database" if "PostgreSQL" in doc else "backend",
        },
        vector={
            "text-dense": d_vec.tolist(),
            "text-sparse": models.SparseVector(
                indices=s_vec.indices.tolist(),
                values=s_vec.values.tolist(),
            ),
        },
    )
    for idx, (doc, d_vec, s_vec) in enumerate(
        zip(documents, dense_vectors, sparse_vectors), start=1
    )
]

client.upsert(collection_name=COLLECTION_NAME, points=points)

3. Server-Side RRF Query With prefetch (and Pre-Filtering!)

Why RRF instead of adding scores together? Dense cosine similarity lives in [-1.0, 1.0], while BM25 / SPLADE scores are unbounded positive floats. Adding them directly distorts ranking.

RRF ignores raw magnitudes and sums reciprocal ranks:

RRF_Score(d) = sum( 1.0 / (k + rank_m(d)) )

With the classic smoothing constant k = 60, rank #1 gets 1/61 = 0.0164 and rank #2 gets 1/62 = 0.0161 — documents that appear near the top of both lists rise cleanly to the top.

Critical production detail: put filters INSIDE Prefetch

If you apply a tenant/ACL filter only on the outer query (post-filtering), each prefetch might return 20 docs that get stripped out afterward, leaving zero hits. Pass filter= into each models.Prefetch:

query_text = "pg_stat_statements slow query"
q_dense = list(dense_model.embed([query_text]))[0].tolist()
q_sparse_raw = list(sparse_model.embed([query_text]))[0]
q_sparse = models.SparseVector(
    indices=q_sparse_raw.indices.tolist(),
    values=q_sparse_raw.values.tolist(),
)

tenant_filter = models.Filter(
    must=[
        models.FieldCondition(
            key="category",
            match=models.MatchValue(value="database"),
        )
    ]
)

results = client.query_points(
    collection_name=COLLECTION_NAME,
    prefetch=[
        models.Prefetch(
            query=q_dense,
            using="text-dense",
            filter=tenant_filter,
            limit=20,
        ),
        models.Prefetch(
            query=q_sparse,
            using="text-sparse",
            filter=tenant_filter,
            limit=20,
        ),
    ],
    query=models.FusionQuery(fusion=models.Fusion.RRF),
    limit=5,
)

for hit in results.points:
    both_pools = hit.score > 0.025  # quick provenance heuristic for k=60
    print(f"ID={hit.id} | RRF={hit.score:.4f} | BothPools={both_pools} | {hit.payload['text']}")

And do not forget to index any payload field you filter on:

client.create_payload_index(
    collection_name=COLLECTION_NAME,
    field_name="category",
    field_schema=models.PayloadSchemaType.KEYWORD,
)

4. Measured Recall, Latency, and Memory Footprint

Benchmarking 300 technical queries (exact symbol names + conceptual questions) against 10,000 engineering docs (Top-5 recall):

Retrieval Mode Exact Technical Keyword Recall Conceptual Question Recall Mean Latency
Pure Dense (1536d Cosine) 0.618 0.912 2.8 ms
Pure Sparse (BM25 / SPLADE) 0.895 0.640 1.9 ms
Hybrid RRF (Dense + Sparse) 0.942 0.928 3.7 ms

Pure dense missed 38%+ of exact symbol matches. Hybrid RRF closed that gap and even nudged conceptual recall up (0.912 → 0.928) for less than 1 ms of extra latency.

Ingestion throughput and RAM footprint (1536d dense + ~42 active sparse tokens/doc, single node):

Corpus Size Batch Upsert Time Throughput Resident RAM
1,000 docs 1.24 s 806 pts/s 14.2 MB
5,000 docs 5.82 s 859 pts/s 68.7 MB
10,000 docs 11.45 s 873 pts/s 135.4 MB

The sparse inverted index added roughly ~18% RAM overhead on top of the dense HNSW index. For multi-million-document collections, turn on scalar quantization for dense vectors and set on_disk=True for sparse indices. (You can estimate dense RAM/disk requirements beforehand with this Vector Storage Calculator.)

Postgres vs Qdrant?

If your stack already lives on PostgreSQL and you are wondering whether Postgres full-text search + vectors is good enough instead of running Qdrant, I also benchmarked both head-to-head in Postgres full-text BM25 + vectors vs Qdrant RRF on 300 SciFact queries.

Full annotated Qdrant guide: aiandsoftwarehub.com.

What sparse retriever are you pairing with dense vectors in Qdrant? Classic BM25, SPLADE via FastEmbed, or miniCOIL?

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.