Are you tired of seeing your vector search miss exact product numbers, API error codes, or customer names?
Vector-only retrieval captures general meaning, yet it struggles when users type exact terms. That gap causes frustrating misses in real support bots, as we detail in our master blueprint on building production RAG systems.
The good news is that adding BM25 keyword search takes less than fifty lines of Python code. In this step-by-step tutorial, we will show you two easy ways to build a hybrid RAG pipeline: using a managed hybrid store (Method 1) and writing your own Reciprocal Rank Fusion retriever in pure Python (Method 2).
Executive Summary
- Why Hybrid Search Wins: Dense vectors handle synonyms and natural questions, while BM25 catches exact serial codes, names, and acronyms.
- Reciprocal Rank Fusion (RRF): A simple math formula merges keyword ranks and vector ranks into one unified relevance list without score scaling headaches.
- Dual Implementation Paths: Choose Qdrant managed hybrid collections for quick setup, or run our zero-lock-in Python BM25 script anywhere.
- Final Precision Filter: Pass merged results through a lightweight cross-encoder before sending context to your language model.
Table of Contents
- Executive Summary
- Vector Search vs BM25 vs Hybrid Retrieval
- Method 1: Managed Hybrid Search With Qdrant (Recommended)
- Method 2: Pure Python Hybrid Retriever With BM25 and RRF
- Common Troubleshooting Questions & How to Fix Them
- Frequently Asked Questions
- Final Thoughts & Next Steps
- Primary Sources & References
Vector Search vs BM25 vs Hybrid Retrieval
| Query Type | Example User Query | Dense Vector Result | BM25 Keyword Result | Hybrid RRF Outcome |
|---|---|---|---|---|
| Conceptual Question | “How do we protect user passwords?” | Finds hashing and encryption docs | Misses docs using word “credentials” | Returns exact encryption policy. |
| Exact Error Code | “Fix error ERR_DB_TIMEOUT_504” | Pulls random database articles | Pinpoints exact error code line | Returns exact timeout fix steps. |
| Negated Condition | “Accounts not eligible for refund” | Confuses “eligible” and “not eligible” | Matches exact words with phrase boosts | Ranks accurate exclusion rules higher. |
Method 1: Managed Hybrid Search With Qdrant (Recommended)
If you want to ship hybrid search quickly without maintaining separate keyword indexes in memory, using a database with native sparse and dense vectors is the easiest path.
Step 1: Install the Qdrant Client and FastEmbed
First, open your terminal and install the Qdrant Python SDK along with FastEmbed for local dense and sparse (BM25-style) vector generation.
pip install qdrant-client fastembedStep 2: Create a Hybrid Collection in Python
Next, create a collection configured to store both standard semantic embeddings and sparse lexical weights inside the same record.
from qdrant_client import QdrantClient, models
client = QdrantClient(":memory:") # Replace with URL for production cluster
client.create_collection(
collection_name="company_docs",
vectors_config={"dense": models.VectorParams(size=384, distance=models.Distance.COSINE)},
sparse_vectors_config={"sparse": models.SparseVectorParams()},
)Step 3: Query Using Built-In Prefetch and RRF Fusion
Finally, send a query using Qdrant’s Prefetch API. The database searches both indexes at once and automatically fuses the rankings using Reciprocal Rank Fusion.
results = client.query_points(
collection_name="company_docs",
prefetch=[
models.Prefetch(query=[0.12, -0.04, ...], using="dense", limit=20),
models.Prefetch(query=models.SparseVector(indices=[12, 88], values=[0.9, 0.5]), using="sparse", limit=20),
],
query=models.FusionQuery(fusion=models.Fusion.RRF),
limit=5,
)Pro Tip: Before deploying your database collection, review our comparison of the 7 best vector databases for RAG in 2026 to compare RAM usage across managed and self-hosted clusters.
Method 2: Pure Python Hybrid Retriever With BM25 and RRF
If you prefer full control over your search weights without locking into a specialized database API, you can write a hybrid retriever in plain Python using rank_bm25 and sentence-transformers.
Step 1: Install Lightweight Python Libraries
First, install rank_bm25 for fast keyword scoring and sentence-transformers for local dense embeddings.
pip install rank-bm25 sentence-transformers numpyStep 2: Index Your Document Chunks
Next, tokenize your chunks for BM25 and generate normalized embeddings for cosine similarity lookup. Keep your document IDs aligned across both arrays.
import numpy as np
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer
docs = [
"Error ERR_504 occurs when upstream proxy timeouts exceed 30 seconds.",
"Always hash user credentials with Argon2id before database storage.",
"Enterprise refund requests are not valid after 14 days of activation.",
]
# Build BM25 keyword index
tokenized_docs = [doc.lower().split() for doc in docs]
bm25 = BM25Okapi(tokenized_docs)
# Build dense vector matrix
embedder = SentenceTransformer("BAAI/bge-small-en-v1.5")
doc_vectors = embedder.encode(docs, normalize_embeddings=True)Step 3: Merge Rankings With Reciprocal Rank Fusion (RRF)
Now, write a short RRF function that scores every document using 1 / (k + rank), where k=60 is the standard smoothing constant. This formula blends keyword rank and vector rank cleanly without worrying about mismatched score scales.
def hybrid_search(query: str, top_k: int = 3, rrf_k: int = 60):
# 1. BM25 keyword ranks
bm25_scores = bm25.get_scores(query.lower().split())
bm25_ranks = np.argsort(bm25_scores)[::-1]
# 2. Dense vector ranks
q_vec = embedder.encode([query], normalize_embeddings=True)[0]
vec_scores = np.dot(doc_vectors, q_vec)
vec_ranks = np.argsort(vec_scores)[::-1]
# 3. Reciprocal Rank Fusion
fused_scores = {}
for rank, doc_idx in enumerate(bm25_ranks):
fused_scores[int(doc_idx)] = fused_scores.get(int(doc_idx), 0.0) + 1.0 / (rrf_k + rank + 1)
for rank, doc_idx in enumerate(vec_ranks):
fused_scores[int(doc_idx)] = fused_scores.get(int(doc_idx), 0.0) + 1.0 / (rrf_k + rank + 1)
ranked_ids = sorted(fused_scores.keys(), key=lambda x: fused_scores[x], reverse=True)
return [(docs[i], fused_scores[i]) for i in ranked_ids[:top_k]]
print(hybrid_search("How do I fix ERR_504?"))Note: After retrieving the top 10 hybrid chunks, generate grounded system instructions using our free TeckScaler Prompt Optimizer so your LLM cites exact document passages cleanly.
Common Troubleshooting Questions & How to Fix Them
Here are the most common snags developers hit when wiring up Python hybrid search:
- Issue: BM25 ignores punctuation inside codes like
ERR_504orv2.4.1. Simple.split()leaves trailing periods or splits unevenly. Strip trailing punctuation with a clean regex tokenizer before feeding words intoBM25Okapi. - Issue: One index dominates the final results. Multiply either the dense RRF term or the sparse RRF term by a weight factor (such as
0.7for vectors and0.3for keywords) based on your dataset tests. - Issue: High memory usage on large document sets. For more than 100,000 chunks, replace in-memory
BM25Okapiwith PostgreSQL full-texttsvectorpaired withpgvector.
Frequently Asked Questions
What does the constant k=60 do in Reciprocal Rank Fusion?
The constant k=60 prevents documents ranked #1 in a single index from dominating too aggressively over documents that rank solidly across both indexes. It was introduced in classic information retrieval research and remains the industry standard default.
Is BM25 still useful when using modern 1536-dimension embeddings?
Yes. Even large neural embedding models compress exact alphanumeric strings like customer IDs, SKU numbers, and version tags, making BM25 essential for high precision.
Does hybrid search slow down my RAG API response time?
Running BM25 alongside vector search adds less than 15 milliseconds on medium datasets, which is barely noticeable compared to the 1 to 3 seconds an LLM takes to generate tokens.
Final Thoughts & Next Steps
We hope this step-by-step tutorial helped you build a clean, reliable hybrid RAG pipeline in Python.
Continue strengthening your retrieval pipeline with these next guides in our RAG cluster:
- Seeing wrong answers or ignored context? Follow How to Fix RAG Hallucinations and Bad Context Retrieval.
- Comparing storage engines? Read 7 Best Vector Databases for RAG in 2026.
- Want the big picture? Revisit The Ultimate Guide to Building Production RAG Systems.
Need engineering help scaling custom search and AI agent pipelines? Connect with our software engineering team at teckscaler.com/contact/.
Published by the TeckScaler Editorial Team. Last updated November 25, 2026.




[…] app catches exact part numbers, API errors, and names. You can follow our hands-on walkthrough on how to build a hybrid RAG pipeline with Python and BM25 to write this retriever step by […]