Hybrid search & RRF
Run keyword (BM25) and vector search in parallel and merge the two rankings, usually with Reciprocal Rank Fusion. Each covers the other's blind spots, so recall rises for little extra cost.
Analogy: Two witnesses: one remembers the license plate exactly, the other remembers what the car looked like. A suspect both of them point to is a far better bet than either witness's favorite.
How it works
- Vectors catch paraphrase but blur exact tokens; BM25 nails
SKU-4471but knows no synonyms. - You can't add raw scores: cosine sits in a narrow band, while BM25 is unbounded and shifts per query.
- RRF uses ranks only, summing 1/(60 + rank) per list, so agreement between retrievers wins.
- Weighted fusion can beat RRF when tuned on labeled queries, but is fragile to outliers and corpus drift.
- Typical pipeline: top ~50 from each retriever, fuse, rerank, keep 3–8.
Check yourself
Answer to mark it learned; your answers aren't scored.
A security review finds a user saw a snippet from a document they can't access. Your hybrid retriever applies the ACL filter in vector search, then fuses with BM25 via RRF. Most likely hole?
Go deeper
Full explanation
Hybrid search runs keyword search (Lexical search & BM25) and vector search in parallel and merges the two ranked lists. Vectors catch paraphrase ("terminate subscription" ≈ "cancel my plan") but blur exact tokens; BM25 nails PENDING_REVIEW or SKU-4471 but knows no synonyms. Together they cover each other's blind spots.
You can't just add the scores: cosine similarity is bounded and often packed into a narrow band, while BM25 is unbounded and its range changes per query. Two fixes:
Reciprocal Rank Fusion (RRF) ignores scores and uses ranks only:
RRF(d) = Σ over lists 1 / (k + rank(d)), with k = 60 (from the original 2009 paper).
Ranked #1 by both lists: 2/61 ≈ 0.033. Ranked #1 by only one: 1/61 ≈ 0.016. Agreement between retrievers beats one retriever's enthusiasm. No normalization, no labels, no tuning: that is why it's the usual default, built into Elasticsearch, OpenSearch, Qdrant and Azure AI Search, and offered by Weaviate as rankedFusion (its default since v1.24 is relative-score fusion).
Weighted score fusion: min-max normalize each list, then α·vector + (1 − α)·bm25. It can beat RRF when α is tuned on labeled queries, but it's fragile to outliers and the best α drifts as the corpus changes.
Typical pipeline: top ~50 from each retriever → fuse → Reranking (cross-encoders) → keep 3–8.
Code RRF, plus the weighted alternative
from collections import defaultdict
def rrf(rankings: list[list[str]], k: int = 60, top_n: int = 50) -> list[tuple[str, float]]:
"""Reciprocal Rank Fusion: uses ranks only, raw scores are ignored."""
fused: dict[str, float] = defaultdict(float)
for ranking in rankings: # one ranked list of doc ids per retriever
for rank, doc_id in enumerate(ranking, start=1):
fused[doc_id] += 1.0 / (k + rank) # k = 60 flattens the gap between #1 and #10
return sorted(fused.items(), key=lambda x: x[1], reverse=True)[:top_n]
def weighted(bm25: dict[str, float], vec: dict[str, float], alpha: float = 0.5):
"""Alternative: min-max normalize each list, then blend. Tune alpha on labeled queries."""
def norm(s: dict[str, float]) -> dict[str, float]:
lo, hi = min(s.values()), max(s.values())
return {d: (v - lo) / ((hi - lo) or 1.0) for d, v in s.items()}
b, v = norm(bm25), norm(vec)
blended = {d: alpha * v.get(d, 0.0) + (1 - alpha) * b.get(d, 0.0) for d in b | v}
return sorted(blended.items(), key=lambda x: x[1], reverse=True)
bm25_ids = ["kb-17", "kb-03", "kb-88", "kb-42"] # from the inverted index
vector_ids = ["kb-42", "kb-17", "kb-91", "kb-05"] # from the ANN index
for doc_id, score in rrf([bm25_ids, vector_ids])[:3]:
print(f"{doc_id} {score:.4f}")
# kb-17 0.0325 (ranks 1 and 2), kb-42 0.0320 (ranks 4 and 1), kb-03 0.0161 (one list only)Real example
A billing help center has 40k articles. Query: "invoice stuck in PENDING_REVIEW after upgrading". BM25 ranks the one article that mentions PENDING_REVIEW #1; vector search has it #31, because the status code means little to the embedding. Vector search ranks "Why hasn't my invoice updated after a plan change?" #1; BM25 has it #12. With RRF (k = 60) they score 1/61 + 1/91 ≈ 0.027 and 1/61 + 1/72 ≈ 0.030, both above anything found by one list only (at most 1/61 ≈ 0.016). The reranker then decides between them.
Trade-offs +3 · −3
+ You gain
- Covers both exact-term and paraphrase queries; usually higher recall than either retriever alone.
- RRF needs no score normalization and no labeled data to work well.
- Cheap: two parallel queries plus microseconds of fusion math.
− You pay
- Two indexes to build, keep in sync and secure, deletes included.
- RRF discards score magnitudes: a near-perfect match and a weak one at the same rank count the same.
- Weighted fusion needs labeled queries to tune α, and the best α varies by query type.
Use it when
The default first stage for production RAG and search, especially when IDs, codes, names or domain jargon mix with natural-language questions.
Avoid it when
Purely conversational corpora with no exact-term queries (measure before assuming), cross-lingual retrieval where BM25 cannot match, or when you cannot operate a second index.
Numbers to know 4
- RRF: score = Σ 1/(k + rank), with k = 60 from Cormack et al. (2009).
- With k = 60: #1 in both lists ≈ 0.033; #1 in only one list ≈ 0.016; rank 10 is worth ~13% less than rank 1.
- Typical shape: top ~50 per retriever → fuse → rerank → keep 3–8.
- Anthropic: contextual embeddings + contextual BM25 cut top-20 retrieval failures by 49%, and by 67% with reranking.
Common pitfalls 4
- Adding raw scores (cosine 0.82 + BM25 14.3): BM25 silently dominates. Fuse ranks, or normalize first.
- Fetching only the top 5 per list: fusion has nothing to rescue. Fetch 20–100 from each.
- Applying the tenant or ACL filter in the vector leg but not the BM25 leg: a data leak through keyword search.
- Tuning α on 20 queries and hard-coding it forever.
Interview questions 2
Answer out loud first, then reveal.
Why RRF instead of adding the two scores?Show answer
Because the scores live on different scales: cosine similarity is bounded and compressed, BM25 is unbounded and its range changes per query, so a naive sum is dominated by BM25. RRF sidesteps calibration by using ranks, 1/(60 + rank) summed across lists. It is robust to outliers and needs no labeled data, which makes it my default. If I have a few hundred labeled queries, I try normalized weighted fusion and keep it only if nDCG@10 beats RRF on a held-out set.
What does k = 60 actually do?Show answer
It sets how top-heavy the fusion is. With k = 60, rank 1 is worth 1/61 and rank 10 is worth 1/70, only ~13% less, so agreement across lists matters more than one list's favorite. With k = 1, rank 1 is worth 1/2 against 1/11 for rank 10, so a single retriever's top pick dominates. 60 came from the original paper's experiments and holds up well across datasets; I would only change it with an eval that shows why.