Production RAG with Hybrid Search: BM25 and Dense Vectors
Standard semantic search (dense vector retrieval) excels at capturing conceptual intent and contextual meaning, but it often struggles with exact keyword matches such as product serial numbers, technical acronyms, or specific proper nouns. Conversely, traditional keyword search (BM25) captures exact lexical matches but misses semantic nuance.
Combining both approaches into a Hybrid Search architecture using Reciprocal Rank Fusion (RRF) provides the best of both worlds, ensuring high recall and precise retrieval for production-grade RAG applications.
1. Environment Setup and Dependencies
Create a virtual environment and install qdrant-client, rank_bm25, sentence-transformers, and supporting libraries.
# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate
# Install hybrid search and vector database dependencies
pip install qdrant-client sentence-transformers rank_bm25 openai
2. Setting Up Qdrant with Named Vectors and Sparse Support
Configure Qdrant to store both dense embeddings (from Sentence Transformers) and sparse token weights (for lexical matching).
from qdrant_client import QdrantClient
from qdrant_client.http import models
# Initialize Qdrant client
client = QdrantClient(path="./hybrid_rag_db")
collection_name = "hybrid_documents"
# Create collection supporting dense embeddings and sparse vectors
client.recreate_collection(
collection_name=collection_name,
vectors_config={
"dense": models.VectorParams(size=384, distance=models.Distance.COSINE)
},
sparse_vectors_config={
"sparse": models.SparseVectorParams(
index=models.SparseIndexParams(on_disk=False)
)
}
)
3. Generating Embeddings and Ingesting Documents
Tokenize your text documents for BM25 sparse representation and encode them into dense vectors before upserting into Qdrant.
from sentence_transformers import SentenceTransformer
from rank_bm25 import BM25Okapi
# Load dense encoder model
encoder = SentenceTransformer("all-MiniLM-L6-v2")
documents = [
"Error code 503: Server overload during peak API traffic.",
"Llama 3 fine-tuning guide using QLoRA and bitsandbytes.",
"Deploying Django applications to AWS EC2 using Nginx and Gunicorn."
]
# Prepare BM25 tokenized corpus
tokenized_corpus = [doc.lower().split() for doc in documents]
bm25 = BM25Okapi(tokenized_corpus)
# Ingest points into Qdrant
points = []
for idx, doc in enumerate(documents):
dense_vector = encoder.encode(doc).tolist()
# Simple sparse representation mapping token hashes/indices
sparse_indices = [hash(word) % 10000 for word in doc.lower().split()]
sparse_values = [1.0] * len(sparse_indices)
points.append(
models.PointStruct(
id=idx,
vector={
"dense": dense_vector,
"sparse": models.SparseVector(indices=sparse_indices, values=sparse_values)
},
payload={"text": doc}
)
)
client.upsert(collection_name=collection_name, points=points)
4. Executing Hybrid Retrieval with Reciprocal Rank Fusion
Query Qdrant using Qdrant's Prefetch API to combine dense semantic scores and sparse keyword scores seamlessly.
def hybrid_search(query_text: str, top_k: int = 3):
query_dense = encoder.encode(query_text).tolist()
query_sparse_indices = [hash(word) % 10000 for word in query_text.lower().split()]
query_sparse_values = [1.0] * len(query_sparse_indices)
# Execute hybrid query with RRF fusion via Qdrant Prefetch
results = client.query_points(
collection_name=collection_name,
prefetch=[
models.Prefetch(
query=query_dense,
using="dense",
limit=top_k
),
models.Prefetch(
query=models.SparseVector(indices=query_sparse_indices, values=query_sparse_values),
using="sparse",
limit=top_k
),
],
query=models.FusionQuery(fusion=models.Fusion.RRF),
limit=top_k
)
return [hit.payload["text"] for hit in results.points]
# Test hybrid search
matches = hybrid_search("Error code 503")
for match in matches:
print(f"Retrieved: {match}")
Conclusion
By implementing Hybrid Search combining BM25 lexical matching and Dense Vectors with Reciprocal Rank Fusion, your RAG application can achieve superior retrieval accuracy across both exact keyword lookups and broad conceptual queries.