5.2 Hybrid Search (BM25 + Vector), RRF & Cross-Encoder Reranking
Upgrade naive vector search to Google-grade retrieval quality: fuse BM25 keyword search with dense vectors using Reciprocal Rank Fusion (RRF) in a single SQL query, then sharpen precision with a Cross-Encoder Reranker.
1. Why Pure Vector Search Fails on Exact Identifiers
Try searching a pure vector-only RAG bot for:
- An exact error code:
ORA-01555orECONNRESET - A product SKU or part number:
TPS7A4700RGWT - A function or flag name:
--max-old-space-sizeorhnsw.iterative_scan
Dense embeddings compress text into smooth semantic concepts ("database snapshot error"), often washing out exact alphanumeric tokens! Meanwhile, classical Lexical Search (BM25 / PostgreSQL Full-Text Search) nails ORA-01555 in 1 ms — but misses conceptual paraphrases.
Production Solution: Never choose one — run both in parallel (Hybrid Search), fuse their rankings with Reciprocal Rank Fusion (RRF), and pass the top 25 candidates through a Cross-Encoder Reranker!
2. Reciprocal Rank Fusion (RRF): Zero-Tuning Score Merging!
How do you combine a BM25 score (unbounded float like 14.82) with a Cosine Similarity score (0.831)? Naive weighted sums (0.7 * cos + 0.3 * bm25) break constantly because BM25 scores swing wildly from 1.2 to 45.0 depending on query length!
Reciprocal Rank Fusion (RRF) ignores raw score scales completely and fuses purely by rank position (1, 2, 3, ...):
RRF_Score(doc) = 1 / (k + rank_vector) + 1 / (k + rank_bm25) (standard smoothing k = 60)
- Document
X: Rank#2in Vector + Rank#3in BM25 →1/62 + 1/63 = 0.0161 + 0.0159 = 0.0320(Shoots to #1!) - Document
Y: Rank#1in Vector + missing in BM25 →1/61 + 0 = 0.0164 - Why
k = 60works like magic: Zero hyperparameter calibration needed, immune to score-scale outliers, and rewards documents corroborated by both semantic meaning and exact keywords!
3. Bi-Encoders vs. Cross-Encoder Rerankers (Recall vs. Precision)
Why do we retrieve Top 25 via Hybrid RRF and then run a Reranker (Cohere Rerank 3.5, Voyage rerank-2, BAAI/bge-reranker-v2-m3) to pick the final Top 5?
| Architecture | How It Computes Relevance | Speed on 10M Docs | Precision | Role in Funnel |
|---|---|---|---|---|
| Bi-Encoder (Embeddings) | Encodes Query and Doc separately into 2 single vectors; compares via 1 dot product | 3 ms (pre-indexed!) | Good (misses subtle negation & multi-word relationships) | Stage 1: Wide Recall (Top 50) |
| Cross-Encoder (Reranker) | Concatenates [CLS] Query [SEP] Doc into one Transformer so every query token attends directly to every document token! | Impossible (10 hours!) — must run only on Top 25 (~60 ms!) | 🏆 Gold-Standard Precision (+15%–28% NDCG!) | Stage 2: Surgical Precision (Top 5) |
4. Wire-Level Trace: Watching Hybrid RRF + Reranking Rescue a Failed Query
#1Stripe Idempotency Keys Guide (sim=0.84) #2 Handling OpenAI 429 Rate Limits (sim=0.82) // Missed Claude '529' doc at #14!
5. Copy-Paste Production SQL: Single-Query Hybrid Search + RRF in PostgreSQL!
One of the cleanest patterns in modern backend engineering — dense HNSW + lexical full-text + RRF fusion in ONE single round-trip to PostgreSQL:
WITH vector_matches AS (
SELECT chunk_id,
ROW_NUMBER() OVER (ORDER BY embedding <=> $1::halfvec) AS vec_rank
FROM doc_chunks
WHERE tenant_id = $2
ORDER BY embedding <=> $1::halfvec
LIMIT 50
),
keyword_matches AS (
SELECT chunk_id,
ROW_NUMBER() OVER (ORDER BY ts_rank_cd(tsv, websearch_to_tsquery('english', $3)) DESC) AS kw_rank
FROM doc_chunks
WHERE tenant_id = $2
AND tsv @@ websearch_to_tsquery('english', $3)
LIMIT 50
),
rrf_fused AS (
SELECT COALESCE(v.chunk_id, k.chunk_id) AS chunk_id,
COALESCE(1.0 / (60 + v.vec_rank), 0.0) +
COALESCE(1.0 / (60 + k.kw_rank), 0.0) AS rrf_score
FROM vector_matches v
FULL OUTER JOIN keyword_matches k ON v.chunk_id = k.chunk_id
ORDER BY rrf_score DESC
LIMIT 25
)
SELECT c.chunk_id, c.breadcrumb, c.content, r.rrf_score
FROM rrf_fused r
JOIN doc_chunks c USING (chunk_id)
ORDER BY r.rrf_score DESC;
Adding Stage-2 Reranking in Python & TypeScript
import voyageai
from openai import OpenAI
vo = voyageai.Client()
oa = OpenAI()
def rerank_and_answer(question: str, rrf_candidates: list[dict]) -> str:
# 1. Cross-Encoder Rerank: 25 RRF candidates -> Top 5 high-precision chunks (~60ms)
reranked = vo.rerank(
query=question,
documents=[c["content"] for c in rrf_candidates],
model="rerank-2-lite",
top_k=5,
)
top_chunks = [rrf_candidates[r.index] for r in reranked.results if r.relevance_score > 0.25]
# 2. Grounded generation on the distilled Top 5
context = "\n\n".join(f"[{c['chunk_id']}] {c['content']}" for c in top_chunks)
return oa.responses.create(
model="gpt-4o-mini",
instructions="Answer strictly using the cited [chunk_id] passages.",
input=f"{context}\n\nQuestion: {question}",
).output_text6. What Breaks in Production (War Stories)
- Using
plainto_tsqueryWithANDOnly in PostgreSQL FTS: In Postgres,plainto_tsquery('english', 'how do I fix error 529 today')requires every single word (fix & error & 529 & today) to appear in the chunk — returning 0 rows just because the doc didn't contain the word"today"! Usewebsearch_to_tsquery(orparadedb / pg_searchtrueBM25) for much smarter lexical recall. - Skipping a Minimum Reranker Score Threshold: Even if the user asks "Who won IPL 2026?" against your Stripe billing docs,
top_k=5still returns the 5 least-bad billing chunks (relevance_score = 0.01)! Drop chunks below a calibrated floor (e.g.,< 0.15) so your LLM cleanly sees<sources></sources>and abstains instead of hallucinating from noise! - Sending 2,000-Token Chunks Into a 512-Token Reranker: Older cross-encoders silently truncate inputs at
512tokens! Use modern long-context rerankers (rerank-v3.54kcontext,voyage-rerank-24k–8k) and keep chunks concise.
Module 5.2 Mastery Check — Hybrid Search, RRF & Reranking
Keep Exploring: Related Lessons & Tools
All Courses →Encode and decode UTF-8 strings, URLs, query parameters, Hex byte streams, and Base64 / Base64URL payloads without data corruption.
Convert Unix epoch seconds/milliseconds to ISO-8601 and local timezones, and bulk-generate UUID v4, time-ordered UUID v7, and sortable ULIDs.