06.8 Hybrid Search
Lesson 06.7 gave you lexical retrieval: BM25, inverted indexes, analysers — precise on exact terms, blind to paraphrase. Lesson 06.3 and 06.4 gave you dense retrieval: embeddings and ANN indexes — good at meaning, weak on identifiers, error codes, SKUs and rare words. Hybrid search runs both and fuses their ranked lists into one. This lesson is the complete engineering treatment: why the two retrievers fail in complementary ways, every fusion algorithm from reciprocal rank fusion to distribution-based score fusion, how each major engine implements hybrid natively, how to size candidate sets and tune weights on your own data, and the operational traps of keeping two indexes in sync.
What you'll learn
- Why dense and lexical retrieval fail differently, and what the evidence actually says about hybrid gains (with the honest caveat that they vary by dataset)
- The architecture: two retrievers, candidate sets, fusion, optional reranking — and where each stage's depth decisions live
- Every fusion method with intuition, formula and parameters: score fusion with min-max/z-score normalisation, Reciprocal Rank Fusion (including the
k=60origin story), Borda count, the classic CombSUM/CombMNZ/CombMAX family, DBSF and relative-score fusion, interleaving, and learned fusion - A pure-Python fusion library you can run today, with real output on hand-made ranked lists
- How Elasticsearch/OpenSearch, Qdrant, Pinecone, Chroma, LanceDB and Redis each do hybrid natively, and how to do it yourself on sqlite-vec, DuckDB, FAISS and S3 Vectors — with verified config, a comparison table and pros/cons per store — plus RRF written in SQL for pgvector + Postgres FTS
- A do-it-yourself
HybridRetrieverover theVectorStoreand BM25 interfaces from 06.5 and 06.7, with concurrent execution and graceful degradation - Candidate-set sizing, deduplication, pagination, caching and partial-failure handling
- How to choose and tune fusion weights with a labelled set — and when hybrid is not worth it
What you don't need
- API keys or running services. Every runnable sample is pure Python standard library on a tiny hand-made corpus; engine snippets are config/query references you can try later.
- Deep BM25 internals — lesson 06.7 owns them; this lesson treats the lexical side as a retriever that returns ranked hits.
- Reranker internals — lesson 06.9 owns the second stage; here it appears only as the stage after fusion.
- Retrieval metrics in depth — lesson 06.10 owns recall@k/MRR/harness design; we use them here and link forward.
Setup
The runnable code needs only Python 3.11+ — no packages, no keys, no services:
uv init hybrid-search --bare --python 3.13 && cd hybrid-search
# or: work in any existing Python 3.11+ projectCopy the five .py files printed in this lesson — fusion.py, hybrid.py, demo_fusion.py, demo.py and tune.py — into your project folder, then python3 demo_fusion.py, python3 demo.py and python3 tune.py (each works standalone once fusion.py/hybrid.py sit beside it). First time with uv? See lesson 03.1, Part 4.
What you must be able to do after this lesson#
- Explain why combining keyword and vector search helps
- Fuse two ranked lists with RRF and weighted scores
- Run hybrid search in a real vector database
- Tune hybrid weights using an evaluation set
- Decide with an ablation whether hybrid is worth it
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Dense search missed the error code — should we just use BM25?" | 1.1 Two blind spots |
| "Everyone says hybrid is better. Is it?" | 1.2 The evidence, honestly |
| "Where does fusion sit in the pipeline?" | 1.3 The architecture |
| "Why can't we just add the BM25 score and the cosine score?" | 2.1 The core problem |
"What's this k=60 in RRF?" |
2.2 Reciprocal Rank Fusion |
| "Should we use alpha weighting or RRF?" | 2.3 Score fusion with normalisation and 5.3 Tuning |
| "Qdrant's RRF default is k=2 but the paper says 60 — which is right?" | 2.2 |
| "How do I do hybrid in pgvector?" | 3.8 RRF in SQL |
| "What if the lexical retriever is down?" | 4.3 Latency and partial failure |
| "When is hybrid overkill?" | Part 7: When hybrid is not worth it |
| "Do the dense and BM25 indexes need to be updated together?" | 9.1 Keeping two indexes consistent |
Part 1: Why hybrid, and the architecture#
1.1 Two blind spots#
Dense retrieval and lexical retrieval make different kinds of mistakes, which is exactly why combining them helps.
Dense retrieval (embeddings + ANN) understands paraphrase and semantics. It fails when the query contains tokens that carry meaning as strings, not as concepts:
- Exact identifiers: error codes (
VPN-ERR-2041), invoice numbers (INV-2042), SKUs, part numbers, API endpoints, HTTP status codes, commit hashes, legal clause numbers. An embedding model was never trained to makeERR-2041close to the chunk that defines it — the string is essentially noise to it. - Rare or domain words: a new product name, an internal acronym, a person's name. If the term is rare in training data, its embedding is poorly placed.
- Negation and fine-grained constraints: "refunds not eligible for gift cards" — embeddings capture topic, not the logical operator.
Lexical retrieval (BM25/FTS) matches the literal terms. It fails when the answer uses different words than the question:
- Paraphrase: "how much vacation do I get?" vs "Full-time employees accrue 1.5 days of paid vacation per month" — they share almost no content words (
get/accrue,much/1.5 days). - Synonyms and cross-language: "car" vs "automobile", "licence" vs "license" (unless the analyser folds them — see 06.7 on analysis).
- Conceptual queries: "why was I charged twice?" won't literally match "duplicate seat charge traced to a provisioning race".
You saw both halves of this in the demo corpus. The dense retriever ranks help-101 ("Install the VPN client…") above help-102 for the error-code query because their vectors are nearly identical — it cannot tell that only help-102 contains the literal string VPN-ERR-2041. The lexical retriever puts help-102 first by a wide margin (score 12.8 vs 2.3 for the next chunk — the runner-up matched only the stopword is, a toy-retriever artefact that 06.7's analyser handles properly).
1.2 The evidence, honestly#
The classic citation is Cormack, Clarke and Büttcher's 2009 SIGIR paper "Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods": across TREC experiments, fusing several retrievers' rankings with a trivial formula beat Condorcet Fuse in every comparison, beat CombMNZ in all but one, and beat the best individual ranking in every experiment except TREC9 (where the best run involved a human in the loop), with no training data and no score calibration. That result is why RRF became the default fusion in Elasticsearch, OpenSearch, Redis, LanceDB and Chroma, and a common choice in Qdrant (which also offers DBSF, see 2.5).
But be precise about what it shows:
- It shows fusion can beat the best single retriever on those TREC collections — newswire and web corpora evaluated with particular metrics. It does not prove hybrid always wins on your handbook corpus.
- The same paper's own pilot table (Table 1) shows how flat the constant is: fusing 30 configurations of one search system on TREC topics 351–400, MAP was 0.2072 at k=0, 0.2123 at k=10, 0.2145 at k=60, 0.2142 at k=100 and 0.2098 at k=500 — so anything from roughly 10 to 100 is fine on that data. That is evidence about
k, not about RRF beating a tuned alternative. - Later work is more nuanced. Bruch, Gai and Ingber's "An Analysis of Fusion Functions for Hybrid Retrieval" (arXiv 2210.11934, revised May 2023) compares RRF with a convex combination (a weighted sum with one weight,
α·dense + (1−α)·lexical, over normalised scores) for exactly the lexical + dense pair. They report that RRF is sensitive to its parameters, that a convex combination beat RRF both in-domain and out-of-domain, that the choice of normaliser matters less than commonly assumed, and that tuning the single weight needs only a handful of labelled queries. The honest reading: RRF is the best default when you have no labelled data; once you have even a small labelled set, a tuned score fusion is a serious challenger — which is why 5.3 makes you test both. (Their analysis covers two retrievers only.) - Another reason hybrid is not optional folklore: the BEIR benchmark (Thakur et al., arXiv 2104.08663) found BM25 "a robust baseline" on zero-shot transfer, with plain dense and sparse retrievers often underperforming it out of domain; reranking and late-interaction models did best on average at a higher computational cost. Lexical matching is a strong floor that dense retrieval has to beat on your data, not a relic.
- Vendor benchmarks (Qdrant, Elastic, Pinecone all publish hybrid-search numbers) are real but promotional: they measure their own stack on their own data.
- On small or clean corpora, one retriever may already saturate recall and hybrid adds latency and complexity for nothing — we quantify this in Part 7.
- On our toy eval set (5.3) lexical-only actually beat dense-only on MRR, because the toy vectors are crude. That is the honest baseline: measure on your data; never assume.
The right mental model: hybrid is cheap insurance with a real cost (a second index to maintain, roughly 2× retrieval latency if serial, more fusion surface to tune). Buy it when your query log shows both failure modes; skip it when it doesn't.
1.3 The architecture#
flowchart LR
Q["user query"] --> QE["query embedding<br/>(embedder API / local model)"]
Q --> LQ["lexical query<br/>(raw text / analysed query)"]
QE --> D["dense retriever<br/>ANN index / VectorStore"]
LQ --> X["lexical retriever<br/>BM25 / FTS index"]
D --> CD["candidate set<br/>k_dense hits"]
X --> CX["candidate set<br/>k_lex hits"]
CD --> F["fusion<br/>RRF / score fusion / DBSF"]
CX --> F
F --> DD["dedupe by chunk/document id<br/>optional metadata boost"]
DD --> R["optional reranker<br/>(cross-encoder — lesson 06.9)"]
R --> TOP["top-k chunks<br/>→ LLM context (Module 07)"]
F -.->|skip| TOPThree separable decisions live in this diagram, and confusing them is the most common hybrid-search bug:
- Candidate generation — how many hits each retriever returns (
k_dense,k_lex). Too small and the right answer never reaches fusion; too large and you pay latency and fuse noise. - Fusion — how the two ranked lists become one (this whole lesson's Parts 2–3).
- Re-ranking — a second, smarter stage over the fused top-N (cross-encoders, LLM rerankers). Lesson 06.9 owns it; note that reranking operates on the fused candidate list, so a bad fusion can starve the reranker of the right candidates.
Part 2: Fusion methods#
2.1 The core problem: incomparable scores#
Each retriever reports scores on its own scale, and the scales move per query:
- Cosine similarity is bounded in
[-1, 1](typically[0.3, 0.8]for relevant chunks). - BM25 is unbounded — a rare term can produce scores in the dozens; its magnitude depends on corpus statistics (IDF) that shift as the corpus grows.
- Learned-sparse scores (SPLADE-style) sit somewhere else again.
Adding them raw is meaningless. Real output from the worked example in demo_fusion.py (three toy rankings, printed in full in 2.8):
--- naive sum of raw scores (the trap)
ticket-78 16.1100
handbook-001 12.4800
contract-9 8.3700
help-101 8.2600
handbook-002 4.4400
contract-10 1.9000
help-102 0.9300ticket-78 wins purely because BM25 gave it 14A.8 — the dense and sparse signals are drowned. Qdrant's docs put it bluntly: a fixed alpha over raw scores "tends to be dominated by whichever retriever has larger raw magnitudes on a given query", and the BM25 scale shifts per query, so no fixed weight stays balanced. Every fusion method below is a different answer to "how do we compare these lists?":
| Family | What it uses | Robust to scale differences? | Preserves score margins? |
|---|---|---|---|
| Rank fusion (RRF, Borda) | positions only | yes — by construction | no |
| Normalised score fusion (min-max, z-score, arctan) | scores, rescaled per query | mostly | yes |
| Distribution fusion (DBSF, relative-score) | scores, rescaled by distribution stats | yes, if scores are calibrated | partially |
| Comb methods (CombSUM, CombMNZ, CombMAX) | raw scores, or score × list-count | no — assumes comparable scales | yes, if scales were comparable |
| Interleaving | positions, round-robin | yes | no |
| Learned fusion | features per (query, doc) | needs training | yes |
The oldest named family predates all of these: the Comb methods from Fox & Shaw's 1994 metasearch work — CombSUM Σ score_r(d), CombMNZ (Σ score_r(d)) × |{r : d appears in r}| (a bonus for appearing in more lists), and CombMAX max_r score_r(d). They are essentially score fusion without normalisation, which is exactly their problem on a BM25+cosine pair: raw scales aren't comparable, so CombSUM is the naive-sum trap shown above. They survive in legacy metasearch engines and some reranker internals where scores are already comparable; treat them as historical baselines and ablation references, not production defaults.
2.2 Reciprocal Rank Fusion#
The workhorse. From the 2009 paper:
RRF_score(d) = sum over rankings r of 1 / (k + rank_r(d))rankis 1-based position in that retriever's list; a doc absent from a list contributes nothing from it.kis a smoothing constant. The paper fixed k = 60 in a pilot study and never changed it; their data showed MAP was nearly flat for k between 10 and 100, so the exact value is not critical.- Intuition: at k=60 the reciprocal is nearly flat — rank 1 contributes
1/61and rank 60 contributes1/120, barely 2× apart — but every appearance still adds something: a doc ranked mid-list by all retrievers can outrank a doc that's #1 for one retriever and absent elsewhere. That's the "consensus bonus" that makes fusion work. Lowering k is what restores top-heaviness: at k=10, rank 1 (1/11) counts ~6.4× rank 60 (1/70).
Weighted RRF multiplies each retriever's contribution by a weight w_r — the standard way to express "trust dense more than lexical for conceptual queries". Note the formula variants differ in indexing: the paper and most engines use 1-based ranks (1/(k + rank)); Qdrant documents zero-based ranks (1/(k + r_d) with r_d from 0) and its default k = 2, not 60 — a deliberate choice because with prefetch top-k ~20, k=60 makes all contributions nearly equal (1/60 vs 1/79 for the top vs 20th result), muting rank differences. Elasticsearch's rank_constant (default 60, minimum 1) and OpenSearch's rank_constant (default 60) follow the paper; LanceDB RRFReranker(K=60); Chroma's Rrf(k=60). When engines disagree on the default, the safe move is to set it explicitly.
Ties: RRF scores are sums of unit fractions — exact ties are rare but possible (symmetric rankings). Engines break them deterministically; in our implementation sorted on score alone is stable, so equal scores keep first-seen order (dicts preserve insertion order) — fine because fused ties at the cutoff are genuinely ambiguous; log them if it matters.
2.3 Score fusion with normalisation#
When you want score margins to matter — "the dense retriever was far more confident" — you fuse normalised scores instead of ranks:
fused(d) = sum_i w_i * norm_i(score_i(d))Two normalisers cover most cases:
- Min-max:
(s − min) / (max − min)per retriever per query →[0, 1]. Simple, but one outlier compresses everything else — if the top hit scores 0.99 and the rest sit at 0.5, all the 0.5s collapse toward 0. - Z-score:
(s − μ) / σper retriever per query → mean 0, std 1. Preserves relative spacing better, but a single dominant outlier inflates σ and shrinks everyone else; and z-scores can go negative, so a "bad" doc on one side can subtract from a good doc on the other. alphaparameterisation (Pinecone single-index):combined = α·dense + (1−α)·sparse, α ∈ [0,1]. Same thing as two weights that sum to 1 — just a different naming convention. Beware which side α weights: in Pinecone's single-index schemeα=1is pure dense,α=0is pure sparse; other tools may weight the text side instead (Redis'sCOMBINE LINEARtakes separateALPHAandBETA). Always check the convention — and set it explicitly, since some client libraries fill in their own default rather than the server's.
Two edge cases deserve an explicit decision:
- Absent docs. Our
score_fusiongives a doc missing from a retriever's list 0 on that retriever — the strict reading of "never surfaced = no credit". The alternative is a floor value (that retriever's minimum or mean normalised score), which is fairer when the retriever's tail was cut bylimitrather than genuinely irrelevant — but it lets a weak retriever vouch for documents it never saw. RRF sidesteps the question entirely: absence just means no term in the sum. - Degenerate inputs. A retriever returning identical scores (or a single hit) has no spread to normalise, and engines disagree on the convention — Qdrant's DBSF emits 0.5, our
_minmaxemits 0.5 while_zscoreemits 0.0. Treat it as engine-specific: check the docs before comparing fused scores across engines.
The failure mode to internalise: normalisation statistics are computed per query over the returned top-k, a small sample. A query where the retriever returns one huge outlier and nine mediocre hits normalises differently than a query with a flat distribution — so the same α behaves differently per query. This is inherent, not a bug; it's why Qdrant recommends RRF as the no-eval-set default.
2.4 Borda count#
Each ranking awards points by position — top gets N, next N−1, etc. (or len − rank + 1); sum across rankings. It's RRF with linear instead of reciprocal decay: the penalty for dropping from rank 1 to 2 equals the penalty from rank 50 to 51. Consequence: Borda is less top-heavy — a doc that's consistently rank ~5 across all retrievers can beat a doc that's rank 1 in one and absent elsewhere. Rarely the right choice for search (you usually want the top of each list to matter more), but it's the simplest possible fusion and a useful baseline in ablations.
2.5 Distribution-based and relative score fusion#
Two engine-specific normalisers worth knowing by name:
- DBSF (Qdrant, v1.11+): per retriever, compute mean μ and sample standard deviation σ of the returned scores, then map
ŝ = (s − (μ − 3σ)) / 6σ— i.e. the 3-sigma range becomes [0, 1] — and sum. Not clipped: scores outside ±3σ stay outside. Degenerate input (all identical scores, or one result) emits 0.5 rather than dividing by zero. Because it uses distribution statistics rather than min/max, a single outlier moves the bounds less than min-max does — but Qdrant's own docs warn the statistics come from the small prefetch top-k, so a dominant outlier can still skew that query, and on well-calibrated retrievers DBSF can beat tuned RRF while on others it loses. Their guidance: eval set → tune weighted RRF; trust raw scores, no eval → DBSF; neither → plain RRF. - Elasticsearch's
linearretriever withminmax: min-max normalise each retriever's scores to [0,1] then weighted-sum — exactly ourscore_fusionwith_minmax(3.1). OpenSearch'snormalization-processorwithmin_maxis the same idea.
2.6 Interleaving and round-robin#
No scores at all: take rank 1 from each list, then rank 2, and so on, deduplicating as you go. Dead simple, perfectly fair across retrievers, and used in federated-search UIs ("results from web / images / news" tabs merged). For a single ranked list it's strictly worse than RRF — it can't express "this retriever is more trustworthy" and it lets a retriever's rank-10 noise displace another's rank-2 gem. Keep it for display-layer merging, not retrieval.
2.7 Learned fusion and learning-to-rank#
The ceiling: treat fusion as a supervised learning problem. For each (query, candidate) pair compute features — dense score, BM25 score, ranks, metadata (recency, field, language), query-type flags — and train a model (linear, gradient-boosted trees like LambdaMART, or a small neural ranker) to predict relevance. Tools like Elasticsearch's learning-to-rank plugin and XGBoost make this accessible; academic LTR is a whole field (lesson 06.10 touches evaluation; LTR itself is beyond scope).
When it's worth it: large labelled sets (thousands of queries), many retrievers or signals to combine, and a team that can maintain the training pipeline. When it's not: under ~hundreds of labelled queries, hand-tuned weighted RRF is hard to beat — Qdrant's docs say exactly this. Learning-to-rank also risks overfitting your eval set; keep a held-out split.
2.8 Try it: the fusion library#
fusion.py — pure Python, no dependencies. Each function takes a list of ranked lists [(id, score), ...] best-first and returns fused (id, score) pairs best-first:
# fusion.py
"""Fusion methods for hybrid search — pure Python, no dependencies.
A "ranked list" is a list of (doc_id, score) tuples ordered best-first.
Every fusion function takes a list of ranked lists (one per retriever)
and returns a fused list of (doc_id, fused_score) tuples, best-first.
"""
from __future__ import annotations
from statistics import mean, stdev
RankedList = list[tuple[str, float]]
def rrf(rankings: list[RankedList], k: float = 60.0,
weights: list[float] | None = None) -> list[tuple[str, float]]:
"""Reciprocal Rank Fusion (Cormack, Clarke & Buettcher, SIGIR 2009).
score(d) = sum over rankings of weight_r / (k + rank_r(d))
rank is 1-based; docs absent from a ranking contribute 0.
"""
if weights is None:
weights = [1.0] * len(rankings)
if len(weights) != len(rankings):
raise ValueError("one weight per ranking")
scores: dict[str, float] = {}
for ranking, w in zip(rankings, weights):
for rank, (doc_id, _) in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + w / (k + rank)
return sorted(((d, s) for d, s in scores.items()), key=lambda p: -p[1])
def borda(rankings: list[RankedList]) -> list[tuple[str, float]]:
"""Borda count: each ranking awards len(ranking)-rank+1 points.
Linear decay — unlike RRF's reciprocal decay, the gap between rank 1
and rank 2 is the same as between rank 50 and rank 51.
"""
scores: dict[str, float] = {}
for ranking in rankings:
n = len(ranking)
for rank, (doc_id, _) in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + (n - rank + 1)
return sorted(((d, s) for d, s in scores.items()), key=lambda p: -p[1])
def _minmax(ranking: RankedList) -> dict[str, float]:
"""Min-max normalise one ranking's scores into [0, 1].
Degenerate input (all scores identical) maps every doc to 0.5 — a
neutral "no information" value. The normalisers disagree on this
convention (_zscore uses 0.0, dbsf follows Qdrant's 0.5), so treat
degenerate handling as engine-specific rather than a bug.
"""
if not ranking:
return {}
vals = [s for _, s in ranking]
lo, hi = min(vals), max(vals)
if hi == lo:
return {d: 0.5 for d, _ in ranking} # all identical: no information
return {d: (s - lo) / (hi - lo) for d, s in ranking}
def _zscore(ranking: RankedList) -> dict[str, float]:
"""Z-normalise one ranking's scores (mean 0, std 1).
Degenerate input maps to 0.0 (see _minmax for why the conventions differ).
"""
if not ranking:
return {}
vals = [s for _, s in ranking]
mu, sigma = mean(vals), stdev(vals) if len(vals) > 1 else 0.0
if sigma == 0:
return {d: 0.0 for d, _ in ranking}
return {d: (s - mu) / sigma for d, s in ranking}
def score_fusion(rankings: list[RankedList], weights: list[float],
normalizer=_minmax) -> list[tuple[str, float]]:
"""Weighted sum of per-ranking normalised scores: sum w_i * norm_i(d).
`normalizer` is _minmax or _zscore. Docs absent from a ranking score 0
on that ranking — a deliberate choice: a doc the retriever never
surfaced gets no credit (the floor-value alternative is discussed in
the lesson text).
"""
if len(weights) != len(rankings):
raise ValueError("one weight per ranking")
normed = [normalizer(r) for r in rankings]
scores: dict[str, float] = {}
for ranking, w, norm in zip(rankings, weights, normed):
for doc_id, _ in ranking:
scores[doc_id] = scores.get(doc_id, 0.0) + w * norm.get(doc_id, 0.0)
return sorted(((d, s) for d, s in scores.items()), key=lambda p: -p[1])
def dbsf(rankings: list[RankedList]) -> list[tuple[str, float]]:
"""Distribution-Based Score Fusion, as implemented by Qdrant (v1.11+).
Per retriever: shat = (s - (mu - 3*sigma)) / (6*sigma), summed across
retrievers. Not clipped to [0,1]; a degenerate (constant) list emits 0.5.
"""
scores: dict[str, float] = {}
for ranking in rankings:
if not ranking:
continue
vals = [s for _, s in ranking]
if len(set(vals)) == 1:
normed = {d: 0.5 for d, _ in ranking}
else:
mu, sigma = mean(vals), stdev(vals)
if sigma == 0:
normed = {d: 0.5 for d, _ in ranking}
else:
lo = mu - 3 * sigma
normed = {d: (s - lo) / (6 * sigma) for d, s in ranking}
for doc_id, _ in ranking:
scores[doc_id] = scores.get(doc_id, 0.0) + normed[doc_id]
return sorted(((d, s) for d, s in scores.items()), key=lambda p: -p[1])
def interleave(rankings: list[RankedList],
top_k: int | None = None) -> list[tuple[str, float]]:
"""Round-robin merge: take rank 1 of each list, then rank 2, ...
Score is a position index (lower = better), negated so the output
sorts best-first like the other fusions.
"""
out: list[tuple[str, float]] = []
seen: set[str] = set()
depth = max((len(r) for r in rankings), default=0)
for i in range(depth):
for ranking in rankings:
if i < len(ranking):
doc_id, _ = ranking[i]
if doc_id not in seen:
seen.add(doc_id)
out.append((doc_id, -float(len(seen))))
return out[:top_k] if top_k else outNow the worked three-way example — a dense list (cosine, bounded), a BM25 list (unbounded), and a learned-sparse list (another scale), over the module's running corpus. Hand-checks first: ticket-78 is rank 4 dense / rank 1 BM25 / rank 3 sparse, so its RRF(k=60) score is 1/64 + 1/61 + 1/63 = 0.047891; contract-10 appears only in BM25 at rank 6 → 1/66 = 0.015152.
# demo_fusion.py
from fusion import rrf, borda, score_fusion, dbsf, interleave, _minmax, _zscore
dense = [
("handbook-001", 0.81), ("handbook-002", 0.74), ("help-101", 0.55),
("ticket-78", 0.49), ("contract-9", 0.31), ("help-102", 0.22),
]
bm25 = [
("ticket-78", 14.2), ("handbook-001", 9.8), ("contract-9", 7.1),
("help-101", 5.4), ("handbook-002", 3.3), ("contract-10", 1.9),
]
sparse = [
("help-101", 2.31), ("handbook-001", 1.87), ("ticket-78", 1.42),
("contract-9", 0.96), ("help-102", 0.71), ("handbook-002", 0.40),
]
rankings = [dense, bm25, sparse]
def show(title, fused, n=8):
print(f"--- {title}")
for doc_id, score in fused[:n]:
print(f" {doc_id:14s} {score:9.4f}")
# What naive score addition does: BM25's ~14 swamps everything.
naive = {}
for r in rankings:
for d, s in r:
naive[d] = naive.get(d, 0.0) + s
print("--- naive sum of raw scores (the trap)")
for d, s in sorted(naive.items(), key=lambda p: -p[1]):
print(f" {d:14s} {s:9.4f}")
print("hand-check RRF(k=60): ticket-78 =", round(1/64 + 1/61 + 1/63, 6),
" handbook-002 =", round(1/62 + 1/65 + 1/66, 6),
" contract-10 =", round(1/66, 6))
show("RRF k=60, equal weights", rrf(rankings))
show("RRF k=60, weights dense=2 bm25=1 sparse=1",
rrf(rankings, weights=[2.0, 1.0, 1.0]))
show("RRF k=10 (sharper top-of-list)", rrf(rankings, k=10.0))
show("Borda count", borda(rankings))
show("min-max linear, weights 0.6/0.2/0.2", score_fusion(rankings, [0.6, 0.2, 0.2], _minmax))
show("z-score linear, weights 0.6/0.2/0.2", score_fusion(rankings, [0.6, 0.2, 0.2], _zscore))
show("DBSF (Qdrant-style)", dbsf(rankings))
show("interleave (round-robin)", interleave(rankings))Real output (pure Python, deterministic — run it yourself):
--- naive sum of raw scores (the trap)
ticket-78 16.1100
handbook-001 12.4800
contract-9 8.3700
help-101 8.2600
handbook-002 4.4400
contract-10 1.9000
help-102 0.9300
hand-check RRF(k=60): ticket-78 = 0.047891 handbook-002 = 0.046665 contract-10 = 0.015152
--- RRF k=60, equal weights
handbook-001 0.0487
help-101 0.0479
ticket-78 0.0479
contract-9 0.0469
handbook-002 0.0467
help-102 0.0305
contract-10 0.0152
--- RRF k=60, weights dense=2 bm25=1 sparse=1
handbook-001 0.0650
help-101 0.0638
ticket-78 0.0635
handbook-002 0.0628
contract-9 0.0623
help-102 0.0457
contract-10 0.0152
--- RRF k=10 (sharper top-of-list)
handbook-001 0.2576
help-101 0.2393
ticket-78 0.2393
contract-9 0.2150
handbook-002 0.2125
help-102 0.1292
contract-10 0.0625
--- Borda count
handbook-001 16.0000
help-101 13.0000
ticket-78 13.0000
contract-9 9.0000
handbook-002 8.0000
help-102 3.0000
contract-10 1.0000
--- min-max linear, weights 0.6/0.2/0.2
handbook-001 0.8824
help-101 0.5925
ticket-78 0.5814
handbook-002 0.5516
contract-9 0.2347
help-102 0.0325
contract-10 0.0000
--- z-score linear, weights 0.6/0.2/0.2
handbook-001 1.0404
help-101 0.2935
ticket-78 0.2825
handbook-002 0.1659
contract-10 -0.2237
contract-9 -0.6250
help-102 -0.9336
--- DBSF (Qdrant-style)
handbook-001 1.9498
ticket-78 1.7786
help-101 1.7014
handbook-002 1.3217
contract-9 1.2813
help-102 0.6536
contract-10 0.3136
--- interleave (round-robin)
handbook-001 -1.0000
ticket-78 -2.0000
help-101 -3.0000
handbook-002 -4.0000
contract-9 -5.0000
help-102 -6.0000
contract-10 -7.0000Read the differences carefully — they are the lesson:
- Naive sum is dominated by BM25's scale;
handbook-001(top-2 everywhere) loses toticket-78purely on BM25 magnitude. - RRF k=60 compresses everything: scores cluster near
1/61 ≈ 0.0164per appearance, so presence in all three lists matters more than rank within one.handbook-002(ranks 2/5/6) nearly tieshelp-101(ranks 3/4/1). Lowerk(k=10) spreads the scores and makes top ranks matter more — visible in the wider spread. - Min-max linear preserves margins:
handbook-001's 0.88 reflects being near-top on all three normalised scales. Butcontract-10scores exactly 0 — it was BM25's worst hit (min-max bottom), and with weight 0.2 on BM25 plus zeros elsewhere it nets nothing. - Z-score can go negative:
help-102sits near the bottom of both the dense and the sparse lists, so both its z-scores are negative (about −1.3 and −0.8) and it ends belowcontract-10, which only the BM25 list surfaced and which therefore picks up just one small negative term. Z-scores preserve spacing but can punish a document for appearing low in a list rather than not appearing at all. - DBSF lands between: magnitude-aware like score fusion, but distribution-normalised so scales can't swamp.
- Interleave ignores scores entirely:
ticket-78at position 2 because it's rank 1 of BM25 (second list consulted), ahead ofhelp-101at position 3 — order depends on retriever ordering, not merit.
Part 3: Native hybrid in the tools#
Most engines now ship a fusion primitive, and the rest can be fused in SQL or Python. The verified state as of November 2026:
3.1 Elasticsearch and OpenSearch#
Elasticsearch has a retriever framework (GA on Elastic Stack and Serverless). An rrf retriever wraps two or more child retrievers — a standard retriever running a BM25-style query and a knn retriever running vector search — and fuses them server-side:
{
"retriever": {
"rrf": {
"retrievers": [
{ "standard": { "query": { "multi_match": { "query": "VPN-ERR-2041", "fields": ["text"] } } } },
{ "knn": { "field": "vector", "query_vector": [0.1, 0.2, 0.3], "k": 50, "num_candidates": 100 } }
],
"rank_constant": 60,
"rank_window_size": 100
}
},
"size": 10
}rank_constant defaults to 60 (min 1) and rank_window_size defaults to 10 — set rank_window_size at least as large as your candidate depth, or the retriever silently truncates each side's list before fusing. Since Elastic Stack 9.2, child retrievers accept a weight in a wrapped {"retriever": ..., "weight": 2.0} format for weighted RRF. The linear retriever is score fusion: per-retriever weight (≥ 0, default 1.0) plus a normalizer (minmax, l2_norm since 9.1, or none) applied before the weighted sum; Elastic's docs warn that none "may bias the result set towards lexical matches" (BM25 scores are larger), and the linear retriever has the same rank_window_size default of 10. Elasticsearch also does three-way fusion natively — its docs show an rrf over an ELSER sparse-vector retriever, a BM25 standard retriever and a knn retriever.
OpenSearch does it differently: a hybrid query (max 5 clauses) whose sub-scores are combined by a search pipeline processor. Two processors exist:
score-ranker-processor— RRF,combination.technique: "rrf",rank_constantdefault 60, per-clauseweightsthat must sum to 1.0 (introduced in OpenSearch 2.19).normalization-processor— score-based: normalises each clause's scores (min_maxand other techniques) then combines them (arithmetic_mean, weighted sum, etc.), preserving score margins.
PUT /_search/pipeline/hybrid-pipeline
{
"description": "RRF over lexical + neural clauses",
"phase_results_processors": [
{
"score-ranker-processor": {
"combination": {
"technique": "rrf",
"rank_constant": 60,
"parameters": { "weights": [0.5, 0.5] }
}
}
}
]
}Both engines keep lexical and vector in one index, which eliminates the dual-write consistency problem of 9.1 — a major operational argument for them.
Pros: mature lexical analysis, RRF and linear fusion in one request, security and scaling features, one index for both legs. Cons: heavier to run than an embedded store; Elasticsearch and OpenSearch differ in API shape, and the OpenSearch pipeline is cluster state. Choose it when keyword quality matters as much as vector quality, or you already run the cluster.
3.2 Qdrant#
The Query API's prefetch runs sub-requests; a fusion query merges them. Two fusion modes:
{"rrf": {}}ormodels.RrfQuery(rrf=models.Rrf(k=..., weights=[...]))— RRF. Default k=2, weights default to 1.0 per prefetch; the weight count must equal the prefetch count. A customkneeds Qdrant v1.16+ andweightsneed v1.17+ (as of November 2026, per Qdrant's hybrid-queries page); on older servers use plain{"fusion": "rrf"}.{"fusion": "dbsf"}ormodels.FusionQuery(fusion=models.Fusion.DBSF)— DBSF (v1.11+), formula in 2.5.
# Qdrant client (illustrative — needs a running Qdrant; see lesson 06.5)
from qdrant_client import QdrantClient, models
client = QdrantClient(url="http://localhost:6333")
results = client.query_points(
collection_name="handbook",
prefetch=[
models.Prefetch(
query=models.TextQuery(text="error code VPN-ERR-2041"), # BM25 on a full-text index
using="content", limit=20),
models.Prefetch(
query=[0.05, 0.15, 0.85, 0.0], # dense vector
using="dense", limit=20),
],
query=models.RrfQuery(rrf=models.Rrf(k=2, weights=[1.0, 1.0])),
limit=10,
)Qdrant also supports sparse vectors (learned sparse like SPLADE, or BM25-as-sparse) as additional prefetches — a three-way prefetch=[dense, bm25_text, sparse_vector] with one fusion query is the multi-representation pattern. Its docs' tuning guidance is worth stealing: split your eval set in two, tune weights on the first half, measure on the second; without an eval set leave weights at default.
One subtlety in Qdrant's weighted RRF: weights scale rank position, not the fused contribution. The documented formula is 1/(k + (r_d + 1)/w_r − 1) over zero-based ranks, so a weight of 3 on a prefetch makes its rank-3 hit score like rank-1 on an unweighted one — different semantics from Elasticsearch's wrapped weight, which multiplies the contribution. Qdrant's tuning guide also warns that weight pairs are only valid for the k they were tuned at, so retune k and weights together.
Pros: flexible fusion options in a dedicated vector engine (weighted RRF, DBSF, sparse vectors, multi-stage prefetch). Cons: you supply the lexical side (full-text index or sparse vectors) and the RRF k=2 default surprises people. Choose it when you want a dedicated vector engine with hybrid and multi-stage queries built in.
3.3 Pinecone#
Two patterns, which Pinecone's hybrid-search page (opened 11 November 2026) now links as guides for its "legacy" vector indexes, next to the newer Documents API below:
- Single index, alpha-scaled query vectors. Store a dense and a sparse vector per record in one index; query both; Pinecone combines server-side. Because sparse (BM25-style) scores are unbounded while dense scores are bounded, you scale the query vectors client-side —
combined = α·dense + (1−α)·sparse— via a helper likehybrid_score_normbefore the request; the index stores raw values.α=1pure semantic,α=0pure keyword. - Separate indexes + client-side RRF. One index for dense, one for sparse, linked by a shared record ID; query each, merge with RRF in your code. More moving parts but supports sparse-only queries, per-index reranking, and integrated embedding.
A newer option on the Documents API: declare a string field with both full_text_search (BM25) and embed config, then either add a text-match filter ($match_phrase/$match_all/$match_any) to narrow candidates before dense ranking (filter-then-rank — keyword as a filter, not a fused signal), or run separate searches and merge client-side.
Pros: fully managed; one index can hold dense and sparse vectors; namespaces give cheap tenant isolation (06.6). Cons: the single-index path makes you scale query vectors by alpha and supply sparse vectors; fusion beyond alpha or client-side RRF is yours to build. Choose it when you want managed infrastructure and are happy with alpha-weighted hybrid or a small client-side RRF.
3.4 Chroma#
The classic collection.query() API has no hybrid mode; the community workaround is client-side RRF over a dense query and a sparse/FTS query (issue #1330 tracks first-class BM25 hybrid). The newer Search API supports it natively — with an important availability caveat: Chroma's docs currently state the Search API is Chroma Cloud-only, with local single-node support planned. The Search/K/Knn/Rrf classes are exported from the open-source chromadb package on main (v1.6.0), but the latest PyPI release was 1.5.9 as of November 2026 — so a plain pip install chromadb may not give you a working local hybrid search yet. Verify against your installed client version and deployment before relying on it:
from chromadb import Search, K, Knn, Rrf
dense_rank = Knn(query="machine learning research", key="#embedding",
return_rank=True, limit=200)
sparse_rank = Knn(query="machine learning research", key="sparse_embedding",
return_rank=True, limit=200)
hybrid_rank = Rrf(ranks=[dense_rank, sparse_rank], weights=[0.7, 0.3], k=60)
search = (Search()
.rank(hybrid_rank)
.limit(20)
.select(K.DOCUMENT, K.SCORE, "title"))
results = collection.search(search)Note Chroma's Rrf formula carries a negative sign internally because Chroma sorts ascending (lower = better) — same math, opposite convention.
Pros: trivial to start, runs embedded, good for prototypes. Cons: native hybrid availability depends on deployment (Search API is Cloud-first); otherwise you write RRF yourself. Choose it when you are prototyping locally, or are on Chroma Cloud and want a built-in Rrf.
3.5 LanceDB#
query_type="hybrid" runs vector + FTS and merges via .rerank(...). RRFReranker (K=60 default) is the default reranker; MRRReranker(weight_vector, weight_fts) is weighted RRF; LinearCombinationReranker (score blending, weight/fill) is deprecated. A normalize argument controls how raw scores are made comparable first.
from lancedb.rerankers import RRFReranker
table.create_fts_index("text")
rows = (table.search("rebel spaceships", query_type="hybrid",
vector_column_name="vector", fts_columns="text")
.rerank(RRFReranker())
.limit(10).to_list())Pros: embedded or serverless, data on local disk or object storage; hybrid is a one-liner with a swappable reranker. Cons: you own scaling and operations beyond a single node; the fusion knobs are reranker objects rather than a server-side query language. Choose it when you want hybrid inside an application process or on cheap object storage, with FTS and vectors in one table.
3.6 Redis#
FT.HYBRID index SEARCH <text query> VSIM @field $vec [KNN …] COMBINE RRF … runs a text leg (BM25STD scorer by default) and a vector leg in one command. COMBINE RRF has WINDOW (default 20 — the same "per-side depth" trap as Elasticsearch's rank_window_size; raise it) and CONSTANT (default 60); COMBINE LINEAR takes ALPHA/BETA weights. EXPLAINSCORE (Redis 8.10+) prints the fusion arithmetic per hit. Redis's page lists Redis Software Flex as not supported.
# Redis 8.4+ (schematic — check the FT.HYBRID page for exact argument counts)
FT.HYBRID idx
SEARCH "@text:(VPN-ERR-2041)"
VSIM @embedding $vec
COMBINE RRF ... WINDOW 50 CONSTANT 60
PARAMS 2 vec <float32-bytes>If you are on an older Redis Query Engine, run one FT.SEARCH for the text leg and one FT.SEARCH ... =>[KNN ...] for the vector leg and fuse client-side with the library from 2.8 or 3.9.
Pros: very low latency; text, tags, numeric filters and vectors in one in-memory engine; RRF and linear combination built in. Cons: everything is held in RAM, so large corpora are expensive; durability and clustering need care. Choose it when you already run Redis for caching or sessions and need fast hybrid over a bounded corpus.
3.7 sqlite-vec, DuckDB VSS, FAISS and S3 Vectors#
These four have no one-line fusion operator, so you fuse them yourself. That is not a drawback so much as a pattern: rank each side, then apply RRF in SQL (below) or in Python (3.9).
-
sqlite-vec + FTS5. Both live in one SQLite file, so RRF is one query (illustrative; the
FULL OUTER JOINneeds SQLite 3.39+):sql WITH dense AS ( SELECT rowid AS id, ROW_NUMBER() OVER (ORDER BY distance) AS r FROM vec_chunks WHERE embedding MATCH :qvec AND k = 50 ), lexical AS ( SELECT rowid AS id, ROW_NUMBER() OVER (ORDER BY rank) AS r FROM fts_chunks WHERE fts_chunks MATCH :q ORDER BY rank LIMIT 50 ) SELECT COALESCE(d.id, l.id) AS id, COALESCE(1.0 / (60 + d.r), 0) + COALESCE(1.0 / (60 + l.r), 0) AS rrf FROM dense d FULL OUTER JOIN lexical l ON d.id = l.id ORDER BY rrf DESC LIMIT 10;Choose it when the app is local-first or edge and the corpus is up to roughly 10^5–10^6 chunks. Con: no tuning knobs beyond what you write, and young vector APIs.
-
DuckDB VSS + the
ftsextension. The same CTE shape works:array_distance(...)for the dense rank and the FTS extension's BM25 match function for the lexical rank (check the extension docs for the exact function name in your version). Choose it when your data is already analytical (Parquet, notebooks) and you want hybrid retrieval in the same engine. Con: the HNSW index is experimental for persistence; verify withEXPLAIN. -
FAISS / hnswlib. These are vector-only libraries. Pair them with a BM25 library (06.7) and use
HybridRetrieverfrom 3.9. Choose it when you need maximum control or a research baseline. Con: no persistence, filtering or CRUD of their own. -
AWS S3 Vectors. It is a vector store with metadata filtering and no built-in lexical leg, so hybrid means a second retriever (for example OpenSearch or Postgres FTS) plus client-side RRF. Choose it when cost per stored vector matters more than latency and lexical search lives elsewhere. Con: higher query latency than in-memory engines, so the dense leg may dominate your latency budget.
3.7b Meilisearch and provider-managed retrieval#
- Meilisearch. Hybrid is driven by a
semanticRatioparameter that tilts a combined keyword + semantic ranking (its docs describe merging "using its smart scoring system"; they do not expose RRF or a normaliser to tune). Treat it as thealphafamily: set it explicitly and tune it on your eval set. Meilisearch's other features are in 06.7, 4.5. - Provider-managed retrieval (OpenAI
file_searchand similar hosted stores). The OpenAI guide describes the tool as using "semantic and keyword search" and shows onlymax_num_resultsand metadatafilters; the API reference and theopenai3.42.1 types addranking_options—ranker,score_thresholdandhybrid_searchweights (embedding_weight,text_weight) — as of November 2026 (07.7 has the details). So you can set coarse fusion weights, but you cannot see the fused scores or swap the fusion method. That is the trade-off Module 07's managed-services lesson weighs; measure it with the same eval set as your own pipeline (06.10).
3.8 RRF in SQL: pgvector + Postgres FTS#
If your vectors live in pgvector and your text in Postgres tsvector, you don't need a second engine — write RRF in SQL. The pattern is three CTEs: rank each side, FULL OUTER JOIN on id, sum 1/(k+rank):
-- hybrid_rrf.sql — run with psycopg (illustrative; needs pgvector + FTS setup
-- from lessons 06.5/06.7 — do not run against a DB in this phase)
WITH dense AS (
SELECT id, embedding <=> %(qvec)s AS dist
FROM handbook_chunks
WHERE tenant = %(tenant)s
ORDER BY dist
LIMIT %(k_dense)s
),
dense_ranked AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY dist) AS r FROM dense
),
lexical AS (
SELECT id, ts_rank_cd(tsv, websearch_to_tsquery('english', %(qtext)s)) AS score
FROM handbook_chunks
WHERE tenant = %(tenant)s
AND tsv @@ websearch_to_tsquery('english', %(qtext)s)
ORDER BY score DESC
LIMIT %(k_lex)s
),
lex_ranked AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY score DESC) AS r FROM lexical
),
fused AS (
SELECT COALESCE(d.id, l.id) AS id,
COALESCE(1.0 / (%(k)s + d.r), 0.0)
+ COALESCE(1.0 / (%(k)s + l.r), 0.0) AS rrf_score
FROM dense_ranked d
FULL OUTER JOIN lex_ranked l ON d.id = l.id
)
SELECT f.id, c.section, c.content, f.rrf_score
FROM fused f
JOIN handbook_chunks c ON c.id = f.id
ORDER BY f.rrf_score DESC
LIMIT %(top_n)s;With k=60, k_dense=50, k_lex=50, top_n=10. Note websearch_to_tsquery accepts Google-style plain text (no FTS syntax to inject — but see 06.7 on sanitising user input regardless), and ts_rank_cd is not BM25 — Postgres FTS scores with its own ranking function; true BM25 in Postgres needs an extension (ParadeDB pg_search, pg_bm25; 06.7 covers them). The same CTE pattern extends to three lists by adding another ranked CTE and joining again — this is how you fuse any number of retrievers in pure SQL.
3.9 DIY hybrid over any two retrievers#
When your retrievers live behind different interfaces — a VectorStore from 06.5, a BM25 index from 06.7, an external API — the pattern is a thin adapter per side plus a fuser. hybrid.py below is the whole thing, runnable today on a toy corpus (hand-made 4-D vectors stand in for real embeddings; ToyLexicalRetriever is a deliberately simple idf-overlap stand-in for 06.7's BM25):
# hybrid.py — retriever protocol, toy implementations, HybridRetriever
from __future__ import annotations
import asyncio
import math
import re
from dataclasses import dataclass
from typing import Protocol
from fusion import rrf, score_fusion, _minmax, dbsf
@dataclass(frozen=True)
class Chunk:
id: str
text: str
vector: tuple[float, ...]
CHUNKS = [
Chunk("handbook-001", "Full-time employees accrue 1.5 days of paid vacation per month, up to 18 days per year.",
(0.90, 0.10, 0.00, 0.00)),
Chunk("handbook-002", "Sick leave is separate from vacation: 10 days per year, no accrual cap.",
(0.85, 0.15, 0.05, 0.00)),
Chunk("handbook-003", "Domestic travel per diem is $75 per day; meals are reimbursed with receipts over $25.",
(0.10, 0.90, 0.00, 0.05)),
Chunk("handbook-004", "Expense reports are reviewed by your manager within 5 business days.",
(0.15, 0.85, 0.05, 0.00)),
Chunk("help-101", "Install the VPN client, sign in with your SSO account, and pick the nearest region.",
(0.00, 0.10, 0.90, 0.00)),
Chunk("help-102", "If the VPN drops, error code VPN-ERR-2041 means the session token expired; reconnect to fix it.",
(0.05, 0.15, 0.85, 0.00)),
Chunk("ticket-77", "Customer asked why the October invoice shows two VPN seat charges.",
(0.20, 0.20, 0.00, 0.80)),
Chunk("ticket-78", "Duplicate seat charge traced to a provisioning race; refund issued.",
(0.20, 0.10, 0.75, 0.20)),
Chunk("contract-9", "Master service agreement: payment terms net-30, liability cap 12 months of fees.",
(0.00, 0.20, 0.10, 0.70)),
Chunk("contract-10", "Renewal notice must be given 60 days before the term ends or it auto-renews.",
(0.05, 0.25, 0.05, 0.65)),
]
QUERY_VECTORS = {
"how much vacation do I get?": (0.95, 0.05, 0.00, 0.00),
"what is error code VPN-ERR-2041?": (0.00, 0.10, 0.85, 0.00),
"why does my October invoice show two VPN seat charges?": (0.20, 0.10, 0.70, 0.25),
"how do I set up the VPN client?": (0.00, 0.05, 0.95, 0.00),
"what are the payment terms in the contract?": (0.00, 0.15, 0.10, 0.75),
"when must we give renewal notice?": (0.00, 0.20, 0.05, 0.70),
"how are expense reports reviewed?": (0.10, 0.90, 0.00, 0.05),
}
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return dot / (na * nb) if na and nb else 0.0
@dataclass(frozen=True)
class Hit:
id: str
score: float
text: str = ""
class Retriever(Protocol):
name: str
def search(self, query: str, top_k: int = 10) -> list[Hit]: ...
class DenseRetriever:
"""Cosine k-NN over stored vectors — stands in for VectorStore.query
plus an embedder (lessons 06.1 and 06.5 own those pieces)."""
name = "dense"
def __init__(self, chunks):
self._chunks = chunks
def search(self, query: str, top_k: int = 10) -> list[Hit]:
qv = QUERY_VECTORS[query]
scored = sorted(((cosine(qv, c.vector), c) for c in self._chunks),
key=lambda p: -p[0])
return [Hit(c.id, s, c.text) for s, c in scored[:top_k]]
_TOKEN = re.compile(r"[a-z0-9]+")
class ToyLexicalRetriever:
"""STAND-IN for lesson 06.7's BM25 index: score = sum of idf over the
distinct query terms present in the chunk. Deliberately simple so the
fusion plumbing is visible; swap in the real BM25 retriever later."""
name = "lexical"
def __init__(self, chunks):
self._chunks = chunks
self._doc_terms = [set(_TOKEN.findall(c.text.lower())) for c in chunks]
n = len(chunks)
df = {}
for terms in self._doc_terms:
for t in terms:
df[t] = df.get(t, 0) + 1
self._idf = {t: math.log((n + 1) / (d + 1)) + 1.0 for t, d in df.items()}
def search(self, query: str, top_k: int = 10) -> list[Hit]:
qterms = set(_TOKEN.findall(query.lower()))
scored = []
for c, dterms in zip(self._chunks, self._doc_terms):
s = sum(self._idf.get(t, 0.0) for t in qterms & dterms)
scored.append((s, c))
scored.sort(key=lambda p: -p[0])
return [Hit(c.id, s, c.text) for s, c in scored[:top_k] if s > 0]
class HybridRetriever:
"""Runs every retriever, dedupes by id, fuses with `fusion(rankings)`
where each ranking is [(id, score), ...] best-first."""
def __init__(self, retrievers, fusion):
self._retrievers = retrievers
self._fusion = fusion
self.name = "+".join(r.name for r in retrievers)
def _fuse(self, results, top_k):
texts, rankings = {}, []
for hits in results:
rankings.append([(h.id, h.score) for h in hits])
for h in hits:
texts.setdefault(h.id, h.text)
return [Hit(d, s, texts.get(d, "")) for d, s in self._fusion(rankings)[:top_k]]
def search(self, query: str, top_k: int = 5) -> list[Hit]:
# Over-fetch: each side contributes top_k*4 candidates; fusion then
# picks the final top_k. (06.4/06.9 own recall vs precision depth.)
results = [r.search(query, top_k=top_k * 4) for r in self._retrievers]
return self._fuse(results, top_k)
async def asearch(self, query: str, top_k: int = 5) -> list[Hit]:
"""Same search with the retrievers run concurrently. Sync retrievers
are pushed to threads; async ones are awaited directly."""
async def run(r):
if hasattr(r, "asearch"):
return await r.asearch(query, top_k=top_k * 4)
return await asyncio.to_thread(r.search, query, top_k=top_k * 4)
results = await asyncio.gather(*(run(r) for r in self._retrievers))
return self._fuse(results, top_k)
def make_retrievers():
return DenseRetriever(CHUNKS), ToyLexicalRetriever(CHUNKS)
# Ready-made fusion configs used by the demos and the tuning sweep.
FUSIONS = {
"rrf k=60": lambda rs: rrf(rs, k=60.0),
"rrf k=60 w=0.7/0.3": lambda rs: rrf(rs, k=60.0, weights=[0.7, 0.3]),
"rrf k=60 w=0.3/0.7": lambda rs: rrf(rs, k=60.0, weights=[0.3, 0.7]),
"linear minmax a=0.5": lambda rs: score_fusion(rs, [0.5, 0.5], _minmax),
"linear minmax a=0.7": lambda rs: score_fusion(rs, [0.7, 0.3], _minmax),
"linear minmax a=0.3": lambda rs: score_fusion(rs, [0.3, 0.7], _minmax),
"dbsf": lambda rs: dbsf(rs),
}The adapters that matter in production are thin: VectorStoreRetriever wraps VectorStore.query(vector, top_k=...) (embedding the query first via the Embedder from 06.1); Bm25Retriever wraps whatever index 06.7 builds (SQLite FTS5, Elasticsearch, rank_bm25 — any object with search(query, top_k) -> [(id, score)]). The fusion function plugs in from fusion.py. demo.py below runs the toy corpus end to end — each retriever alone, HybridRetriever with RRF and with weighted min-max fusion, and the async path — printing top-3 with a text snippet:
# demo.py — run the toy retrievers and HybridRetriever end to end
import asyncio
from fusion import rrf, score_fusion, _minmax
from hybrid import make_retrievers, HybridRetriever
ERROR_QUERY = "what is error code VPN-ERR-2041?"
INVOICE_QUERY = "why does my October invoice show two VPN seat charges?"
VACATION_QUERY = "how much vacation do I get?"
def show_hits(hits, label):
print(f"--- {label}")
for h in hits:
print(f" {h.id:14s} {h.score:9.4f} {h.text[:60].rstrip()}")
def main():
dense, lexical = make_retrievers()
# Single retrievers on the exact-identifier query.
show_hits(dense.search(ERROR_QUERY, top_k=3), "dense only: error-code query")
show_hits(lexical.search(ERROR_QUERY, top_k=3), "lexical only: error-code query")
# Fused retrievers: RRF on the identifier query, weighted min-max
# linear fusion on the mixed invoice query.
h_rrf = HybridRetriever([dense, lexical], lambda rs: rrf(rs, k=60.0))
show_hits(h_rrf.search(ERROR_QUERY, top_k=3), "hybrid RRF k=60: error-code query")
h_lin = HybridRetriever([dense, lexical],
lambda rs: score_fusion(rs, [0.6, 0.4], _minmax))
show_hits(h_lin.search(INVOICE_QUERY, top_k=3),
"hybrid linear min-max w=(0.6, 0.4): invoice query")
# Async path — the retrievers run concurrently via asyncio.gather.
async def go():
hits = await h_rrf.asearch(VACATION_QUERY, top_k=3)
print("--- async hybrid RRF: vacation query")
for h in hits:
print(f" {h.id:14s} {h.score:9.4f}")
asyncio.run(go())
if __name__ == "__main__":
main()Real output (pure Python, deterministic — run python3 demo.py):
--- dense only: error-code query
help-101 1.0000 Install the VPN client, sign in with your SSO account, and p
help-102 0.9967 If the VPN drops, error code VPN-ERR-2041 means the session
ticket-78 0.9366 Duplicate seat charge traced to a provisioning race; refund
--- lexical only: error-code query
help-102 12.8306 If the VPN drops, error code VPN-ERR-2041 means the session
handbook-002 2.2993 Sick leave is separate from vacation: 10 days per year, no a
handbook-003 2.2993 Domestic travel per diem is $75 per day; meals are reimburse
--- hybrid RRF k=60: error-code query
help-102 0.0325 If the VPN drops, error code VPN-ERR-2041 means the session
help-101 0.0320 Install the VPN client, sign in with your SSO account, and p
handbook-003 0.0310 Domestic travel per diem is $75 per day; meals are reimburse
--- hybrid linear min-max w=(0.6, 0.4): invoice query
ticket-78 0.6073 Duplicate seat charge traced to a provisioning race; refund
ticket-77 0.5610 Customer asked why the October invoice shows two VPN seat ch
help-102 0.5468 If the VPN drops, error code VPN-ERR-2041 means the session
--- async hybrid RRF: vacation query
handbook-001 0.0328
handbook-002 0.0323
ticket-78 0.0159Note what fusion did on the error-code query: help-102 was lexical rank 1 and dense rank 2 — the consensus bonus puts it first even though dense alone preferred help-101. And on the invoice query, ticket-77 (the chunk that literally contains "October invoice … two VPN seat charges") loses the top spot to ticket-78 under both fusions because ticket-78 appears high on both lists — the classic "keyword-matching question vs answering chunk" tension. Whether that's right depends on what the user wanted; that's what your eval set is for (5.3).
3.10 Comparison table#
| Engine | Hybrid primitive | Fusion methods | Defaults (Nov 2026) | Notes |
|---|---|---|---|---|
| Elasticsearch | rrf / linear retrievers |
RRF (weighted since 9.2), weighted linear w/ minmax·l2_norm·none | rank_constant 60, rank_window_size 10 | One index; ELSER sparse supported as third leg |
| OpenSearch | hybrid query + search pipeline |
RRF (score-ranker-processor), normalised score (normalization-processor) |
rank_constant 60; ≤5 clauses | Pipeline is cluster state — version it |
| Qdrant | Query API prefetch + fusion |
RRF, DBSF | RRF k=2; DBSF v1.11+ | Sparse vectors = third leg; prefetch limit ≥ limit+offset |
| Pinecone | single-index alpha / two-index client RRF / Documents text-match filter | RRF client-side; server-side alpha scaling | α is your choice | Sparse scores unbounded → must normalise |
| Chroma | Search API Rrf (new); classic API = DIY |
RRF (k=60, weights) | n/a | Search API documented as Chroma Cloud-only (Nov 2026) |
| LanceDB | query_type="hybrid" + .rerank() |
RRFReranker (default), MRRReranker, LinearCombination (deprecated) | K=60 | Embedded; also provider rerankers |
| Redis 8.4+ | FT.HYBRID (SEARCH + VSIM + COMBINE) |
RRF (WINDOW 20, CONSTANT 60) or LINEAR (ALPHA/BETA) |
WINDOW 20 | EXPLAINSCORE in 8.10+ |
| pgvector + FTS | DIY in SQL | RRF via CTEs (any fusion writable in SQL) | k=60 typical | No second engine to sync |
| sqlite-vec / DuckDB VSS | DIY in SQL (FTS5 / fts extension) |
RRF via CTEs | k=60 typical | Embedded; one file |
| FAISS / hnswlib | DIY in Python | Any (3.9) | — | Pair with a BM25 library |
| AWS S3 Vectors | DIY (no lexical leg) | Client-side RRF with another retriever | — | Cost-first; higher latency |
Choose by situation
| If you... | Prefer | Because |
|---|---|---|
| already run Postgres | pgvector + FTS in SQL | one system, transactional, no sync |
| need the best keyword relevance plus vectors | Elasticsearch or OpenSearch | mature analyzers and built-in fusion |
| want a dedicated vector engine with fusion options | Qdrant | prefetch, weighted RRF, DBSF, sparse vectors |
| want managed and minimal ops | Pinecone | alpha-scaled single index, no servers |
| are building embedded or serverless | LanceDB, or sqlite-vec / DuckDB | hybrid in-process, data in files or object storage |
| need very low latency on a bounded corpus | Redis | in-memory FT.HYBRID |
| are cost-bound on a huge, cold corpus | S3 Vectors + another lexical retriever | cheapest storage, fuse client-side |
Part 4: Candidate-set design#
Deep-dive
Fusion can only rank what the retrievers returned. Everything before fusion is candidate-set engineering.
4.1 How many from each side#
Each retriever contributes k_dense / k_lex candidates; fusion emits the final top-N. Rules of thumb, all tunable on your eval set:
- Over-fetch relative to final N: if you return 5 chunks to the LLM, fetch 30–100 per side (deeper if a reranker follows — 4.4 fuses at ~100–200 per side then). RRF needs the relevant doc to appear somewhere in each list to earn its consensus bonus; a doc ranked 40th lexically still contributes
1/(60+40). - Lexical side can be shallower than dense on conceptual corpora (BM25's tail is noise); deeper when queries are identifier-heavy.
- If a reranker follows (06.9), the fused list should be ~50–200 candidates — rerankers are accurate but expensive per candidate.
- Cost: each extra candidate is one row scored and one payload fetched. At 10⁶ chunks,
k=100per side is trivial for the index but watch payload size — fetch text only for the fused top-N, not the whole candidate pool.
4.2 Deduplication and ID normalisation#
- Same chunk, two retrievers: expected — fusion handles it. Different chunks of the same document: the failure mode. If
handbook-001andhandbook-002are adjacent chunks of one policy, hybrid may return both and crowd out diversity. Options: dedupe bydoc_idkeeping the best-scoring chunk (a "group by document" step — 06.6 covers the general pattern), or let 06.9's reranker see them and rely on MMR-style diversity there. - ID formats must match exactly:
handbook-001vshandbook_001vs a Qdrant integer point ID are different strings to fusion — the doc scores from only one side. Normalise IDs at the adapter boundary (theVectorStoreadapters in 06.5 already derive stable IDs; make the lexical side use the same scheme — 05.8 owns ID design). - Same content, different chunking: if the dense index and the lexical index were built with different chunk boundaries (a classic migration accident), fusion compares apples to oranges —
chunk-17aandchunk-17bmay be the same paragraph split differently. Keep chunking identical across both indexes, versioned together (05.9).
4.3 Latency and partial failure#
Run both retrievers in parallel — serial hybrid doubles latency for nothing. In async Python, asyncio.gather (mechanics in 03.9); our HybridRetriever.asearch shows the pattern including asyncio.to_thread for sync retrievers. Budget: hybrid latency ≈ max(t_embed + t_dense, t_lex) + t_fusion, not the sum of everything — assuming both legs are I/O bound. Note that the dense leg also pays for the query-embedding call, which can dominate it when the embedder is a hosted API (a network round trip; see 06.2 — measure yours), while the lexical leg needs no model.
Partial failure policy — decide before production, not during an incident:
| Lexical side fails | Dense side fails |
|---|---|
| Degrade to dense-only (still semantic) | Degrade to lexical-only (still exact) |
| Or fail the request if exact-match recall is contractual | Or fail if the product is "AI search" and lexical-only feels broken |
Implement degradation explicitly, and make the caller able to see it. The trick is asyncio.gather(..., return_exceptions=True): without it the first exception cancels the whole await; with it every retriever's outcome (hits or exception) comes back, and you fuse the survivors. resilient.py extends hybrid.py — copy it beside the other files:
# resilient.py — graceful degradation for HybridRetriever (continues hybrid.py)
import asyncio
from fusion import rrf
from hybrid import HybridRetriever, ToyLexicalRetriever, DenseRetriever, CHUNKS
class FlakyRetriever:
"""Wraps a retriever and raises on demand — a stand-in for a down index."""
def __init__(self, inner, fail: bool = False):
self._inner, self.fail = inner, fail
self.name = inner.name
def search(self, query: str, top_k: int = 10):
if self.fail:
raise ConnectionError(f"{self.name} index unreachable")
return self._inner.search(query, top_k=top_k)
class ResilientHybridRetriever(HybridRetriever):
"""Like HybridRetriever, but one retriever failing does not fail the query.
Returns (hits, served_by): `served_by` lists the retrievers that answered,
so callers can log WHICH mode served each query (a silent fallback hides
a broken index for weeks). If every retriever fails, raise.
"""
async def asearch_resilient(self, query: str, top_k: int = 5):
async def run(r):
if hasattr(r, "asearch"):
return await r.asearch(query, top_k=top_k * 4)
return await asyncio.to_thread(r.search, query, top_k=top_k * 4)
outcomes = await asyncio.gather(*(run(r) for r in self._retrievers),
return_exceptions=True)
ok = [(r, o) for r, o in zip(self._retrievers, outcomes)
if not isinstance(o, BaseException)]
for r, o in zip(self._retrievers, outcomes):
if isinstance(o, BaseException):
print(f"WARN retriever={r.name} failed: {o!r}") # use logging + a metric
if not ok:
raise RuntimeError("all retrievers failed")
hits = self._fuse([o for _, o in ok], top_k)
return hits, [r.name for r, _ in ok]
async def main():
q = "what is error code VPN-ERR-2041?"
dense, lexical = DenseRetriever(CHUNKS), ToyLexicalRetriever(CHUNKS)
flaky_lex = FlakyRetriever(lexical)
hybrid = ResilientHybridRetriever([dense, flaky_lex], lambda rs: rrf(rs, k=60.0))
for fail in (False, True):
flaky_lex.fail = fail
hits, served_by = await hybrid.asearch_resilient(q, top_k=2)
print(f"lexical_down={fail} served_by={served_by} top={[h.id for h in hits]}")
if __name__ == "__main__":
asyncio.run(main())Real output (pure Python, deterministic — run python3 resilient.py):
lexical_down=False served_by=['dense', 'lexical'] top=['help-102', 'help-101']
WARN retriever=lexical failed: ConnectionError('lexical index unreachable')
lexical_down=True served_by=['dense'] top=['help-101', 'help-102']Look at what happened to the ranking: with the lexical side down, the exact-identifier winner help-102 drops to second place — dense alone prefers help-101, exactly the failure 1.1 predicted. A degraded answer is worse for identifier queries specifically, which is why the served_by list matters: log it on every query (and expose a counter such as hybrid_degraded_total{missing="lexical"}), alert when it is non-zero for more than a few minutes, and consider showing identifier-heavy users a "search is degraded" notice. Fusing a single list with RRF is harmless (it just reproduces that retriever's order), so no special-casing of the fused scores is needed; just do not compare them with scores from a healthy two-retriever run. A silent degradation hides a broken BM25 index for weeks. Also note embedding-API failure (06.2 covers query-path latency): if the embedder is down you can't even form the dense query — have a lexical-only fallback path ready.
4.4 Pagination#
ANN and FTS paginate differently (offset vs cursor — 06.5/06.6 own the details). For hybrid: fuse deep — ~100–200 per side when a reranker will consume the pool (06.9), ~30–100 per side when you serve the fused list directly (4.1) — then paginate the fused list — never paginate each side independently and merge pages, or page 2 will re-show page-1 hits and miss docs that only ranked well in fusion. Deep fused pagination is cheap because fusion already materialised the union; expose a cursor over fused rank position.
4.5 Caching#
Two cache layers matter: the query embedding (repeated queries skip the embedder call — 06.2 owns it; note privacy: cached queries are stored user text) and the fused result list for hot queries (TTL minutes, invalidated on index writes). Cache the fused top-N, not per-retriever results — retriever-level caching breaks when only one side's index changed.
Part 5: Weighting and tuning#
5.1 Choosing weights and alpha#
You have three knobs: per-retriever weights (weighted RRF or score fusion), the fusion constant k, and per-side candidate depth. Start at equal weights + RRF + your engine's documented k — it's the only configuration with published evidence of robustness. Then change one thing at a time, measured on your eval set (5.3).
5.2 Query routing#
Not every query wants the same blend. A cheap, effective pattern: route by query type, then fuse with type-appropriate weights — or even bypass fusion for extreme cases.
| Query looks like… | Signal | Action |
|---|---|---|
Contains IDs/codes/SKUs/version strings (ERR-, INV-, v2., #) |
regex/heuristic | lexical weight ↑ or lexical-only |
| Very short (1–3 content words) | token count | lexical ↑ — dense on "vpn setup" is noise-prone |
| Long natural-language question | token count + syntax | dense ↑ |
| Mixed | default | balanced hybrid |
Implement the router as a pure function returning weights — testable, no model needed. An LLM can do the routing too (classify query intent → pick weights), at the cost of a model call per query; that's a Module 07 query-understanding pattern — preview only. Per-language routing matters too: if your lexical analyser is English-only but dense handles 50 languages, down-weight lexical for non-English queries (06.7 on per-language fields, 06.6 on lang filters).
5.3 Tuning with a labelled set#
The harness from tune.py — seven labelled queries over the toy corpus, sweep fusion configs, report recall@5 and MRR@5:
# tune.py — sweep fusion configs on a labelled set (pure Python)
from hybrid import make_retrievers, FUSIONS, HybridRetriever
LABELLED = [
("how much vacation do I get?", {"handbook-001"}),
("what is error code VPN-ERR-2041?", {"help-102"}),
("why does my October invoice show two VPN seat charges?", {"ticket-78"}),
("how do I set up the VPN client?", {"help-101"}),
("what are the payment terms in the contract?", {"contract-9"}),
("when must we give renewal notice?", {"contract-10"}),
("how are expense reports reviewed?", {"handbook-004"}),
]
K = 5
def metrics(ids, relevant):
top = ids[:K]
recall = len(set(top) & relevant) / len(relevant)
rr = next((1.0 / (i + 1) for i, d in enumerate(top) if d in relevant), 0.0)
return recall, rr
def evaluate_rankings(rankings_per_query):
rec = [metrics(ids, rel)[0] for ids, (_, rel) in zip(rankings_per_query, LABELLED)]
mrr = [metrics(ids, rel)[1] for ids, (_, rel) in zip(rankings_per_query, LABELLED)]
return sum(rec) / len(rec), sum(mrr) / len(mrr)
def rankings_for(retriever):
return [[h.id for h in retriever.search(q, top_k=K * 4)] for q, _ in LABELLED]
def rankings_for_fusion(fusion, retrievers):
h = HybridRetriever(retrievers, fusion)
return [[x.id for x in h.search(q, top_k=K)] for q, _ in LABELLED]
def main():
dense, lexical = make_retrievers()
print(f"{'config':22s} {'recall@5':>8s} {'MRR@5':>7s}")
for name, retriever in [("dense only", dense), ("lexical only", lexical)]:
rec, mrr = evaluate_rankings(rankings_for(retriever))
print(f"{name:22s} {rec:8.3f} {mrr:7.3f}")
for name, fusion in FUSIONS.items():
rec, mrr = evaluate_rankings(rankings_for_fusion(fusion, [dense, lexical]))
print(f"{name:22s} {rec:8.3f} {mrr:7.3f}")
if __name__ == "__main__":
main()Real output:
config recall@5 MRR@5
dense only 1.000 0.786
lexical only 1.000 0.929
rrf k=60 1.000 0.929
rrf k=60 w=0.7/0.3 1.000 0.929
rrf k=60 w=0.3/0.7 1.000 1.000
linear minmax a=0.5 1.000 0.929
linear minmax a=0.7 1.000 1.000
linear minmax a=0.3 1.000 0.929
dbsf 1.000 0.929Read this honestly: on this toy set every config hits recall@5 = 1.0 — the corpus is too small and the queries too easy to separate them. The MRR differences are real but tiny-sample noise. This is exactly why 06.10 exists: you need hundreds of queries, a held-out split, and metrics that discriminate. What the toy does show honestly: (a) lexical-only beat dense-only on MRR — "hybrid always wins" is false until measured; (b) the plumbing works end-to-end; (c) weight changes do move rankings (w=0.3/0.7 flipped MRR to 1.000). Scale the same harness to your real question set and the differences become meaningful. Split queries into tune/validation halves — tuning and measuring on the same queries inflates results (Qdrant's docs say the same).
Part 6: Beyond two retrievers#
Deep-dive
6.1 Three-way and multi-vector hybrid#
The architecture extends to N retrievers: prefetch=[dense, bm25_text, sparse_vector] in Qdrant, three children in an Elasticsearch rrf, three retrievers in a SQL or Python RRF. Two common three-way patterns:
- Dense + BM25 + learned sparse (SPLADE/BGE-M3 sparse output — 06.7 covers the models): dense for semantics, BM25 for exact terms, learned sparse for expansion — it matches synonyms the query didn't literally contain. Fusion treats all three equally by default; weight the learned-sparse leg lower until your eval says otherwise.
- Multi-vector per side: separate dense vectors for title vs body (06.5 data modelling), fused the same way — each vector field is just another ranking. The score-comparability problem is identical; RRF remains the safe default.
6.2 Multi-collection fusion#
Searching several collections (per language, per source, per tenant shard) then merging has the same score-comparability problem squared: scores from different collections aren't just different scales, they're different distributions. RRF is the safe default — it only needs ranks. Score fusion across collections requires per-collection normalisation and a calibration assumption you probably can't verify. Deduplicate by global doc ID across collections before fusion, and remember each collection's k contributes independently to the fused score — a doc that tops two collections outranks a doc that tops one, which is usually what you want but worth a sanity check.
6.3 Metadata-aware boosting#
Fusion produces a relevance score; business logic often wants more. Recency, popularity, authority, freshness — multiply or add a boost after fusion (or as a feature in learned fusion):
from hybrid import Hit # the dataclass from hybrid.py (id, score, text)
def boost(hits: list[Hit], meta: dict[str, dict], w_recency=0.1) -> list[Hit]:
"""Score *= (1 + w * recency_signal). Keep it monotone and bounded —
a boost that can flip a 0.03 RRF score past a 0.05 one needs tuning too."""
out = []
for h in hits:
m = meta.get(h.id, {})
age_days = m.get("age_days", 365)
recency = 1.0 / (1.0 + age_days / 365.0) # 1.0 fresh -> ~0.5 old
out.append(Hit(h.id, h.score * (1 + w_recency * recency), h.text))
return sorted(out, key=lambda h: -h.score)Cautions: boosts applied before fusion distort the normalisation statistics; apply them to the fused score. Keep boosts small and bounded — an unbounded popularity boost will eventually surface viral-but-irrelevant chunks above correct answers. And log the pre-boost and post-boost ranks in evals, or you'll never know whether a regression came from retrieval or boosting.
Part 7: When hybrid is not worth it, and the ablation procedure#
Hybrid is not free: a second index to build/maintain/synchronise, ~2× candidate-generation cost, fusion complexity, and another thing to tune. Skip it when:
- Tiny corpora (< ~10k chunks): brute-force dense over everything is already exact; adding BM25 buys recall you can get by fetching top-100 dense.
- No exact-term queries in the log: if your queries are all conceptual ("how do I…"), lexical adds nothing — check your query logs before assuming.
- Single-retriever saturation: if dense-only already hits recall@10 ≈ 1.0 on your eval set, hybrid can't improve recall — only reorder.
- Latency/cost budgets: two indexes = two query paths; on edge or cost-sensitive deployments, one engine doing both (Elasticsearch, OpenSearch, or Postgres with pgvector and FTS) halves the ops surface.
The ablation procedure — run it before committing to hybrid:
- Build your labelled query set (06.10 owns the methodology; Module 05's synthetic-question generation applies).
- Evaluate three configs on the same queries: BM25-only, dense-only, hybrid (RRF, equal weights). Record recall@k and MRR.
- Hybrid wins if it beats both singles on your primary metric by a margin that exceeds your noise floor (split-half variance). If it merely matches the better single, prefer the single — simpler ops.
- Only then tune weights/k (5.3), and only on a train split.
Part 8: Query-side preprocessing for hybrid#
Deep-dive
The two retrievers want different query shapes — treat them separately:
- Dense side wants natural language: full question, stopwords intact (the embedder was trained on sentences), maybe expanded/re-written for recall (07 owns query rewriting for RAG — preview: an LLM rewrite "how much vacation" → "vacation days accrued per month policy" can help dense recall).
- Lexical side wants terms: strip stopwords if your analyser doesn't, keep identifiers verbatim (
VPN-ERR-2041must survive tokenisation — check 06.7's analysis chain preserves codes), possibly extract keyphrases rather than the raw sentence (a 200-word pasted error log as a BM25 query is mostly noise — cap or keyphrase-extract it). - Very short queries ("vpn", "refund"): lexical is precise but ambiguous; dense helps disambiguate — keep both, weight lexical higher only if eval says so.
- Very long queries (pasted stack trace, whole email): dense embeds truncate at the model's max input (06.1); lexical scores diffuse across hundreds of terms. Extract the salient terms/code first — often an LLM extraction step (schema-constrained, 03.4) that emits
{search_terms, error_codes, question}and feeds each retriever its slice. - Filters are not fusion: tenant/language/date constraints apply inside each retriever's candidate generation (06.6) — never post-filter the fused list, or you'll return fewer than k and re-introduce the post-filtering recall collapse that lesson covers.
Part 9: Operational concerns#
Deep-dive
9.1 Keeping two indexes consistent#
The deepest hybrid cost: two indexes must reflect the same corpus state. If the dense index has chunk v3 and the lexical index still has v2, fusion compares different text under one ID — subtle, silent relevance bugs. Options, in order of preference:
- One engine, both representations (Elasticsearch/OpenSearch, Postgres with pgvector and FTS, Pinecone single-index, Qdrant dense+sparse, Redis): one write path, one consistency domain. Strongly preferred when feasible.
- Dual-write with a transactional outbox: write chunk → outbox row → async workers update each index; reconcile on lag alerts. Acceptable but you now own distributed-systems problems (ordering, retries, partial failure).
- Single source of truth + rebuild: store chunks in your DB, treat both indexes as derived and rebuildable — version indexes by corpus generation ID and cut over atomically (05.9 owns ingestion/incremental updates; blue/green reindexing lives there too).
Deletes are the sharp edge: a hard-deleted chunk must vanish from both indexes; soft-delete + compaction per 06.4 applies to each side independently.
9.2 Reindexing and cost#
Model or analyser changes force re-embedding or re-analysis — and hybrid means both pipelines must re-run and cut over together, or you fuse new dense vectors with stale lexical stats (IDF drift — 06.7 covers corpus-statistics drift). Budget reindex cost as 2 × single-index cost plus a consistency window; run shadow reads (query old+new fusion, compare) before cutover.
9.3 Cost of two retrievers#
Per query the arithmetic is small but worth writing down:
candidate volume = k_dense + k_lex e.g. 100 + 100 = 200 hits
payload fetched ≈ (k_dense + k_lex) × ~1 KB/chunk ≈ 200 KB per query
fusion compute = O(C log C) over C ≈ |union| ≈ 200 → microseconds, negligible
query latency ≈ max(t_embed + t_dense, t_lex) + t_fusion (parallel — 4.3)At 100 QPS that is ~20 MB/s of candidate payload — fetch text only for fused survivors and cache hot queries (4.5). Plus 1 embedder call per query. The real costs are storage (two indexes: a full-precision 1,536-dimension float32 vector is about 6 KB per chunk, while BM25 postings for a short chunk are usually smaller but not free, and positions or stored text add more) and ops (two backends' upgrades, backups, monitoring). Compute the break-even: if hybrid lifts recall@10 by X% on your eval, is X% fewer "I couldn't find it" tickets worth the infra? Sometimes yes; sometimes the honest answer is dense-only plus a contains filter for the identifier cases (06.6).
9.4 Monitoring each side's contribution#
Instrument per retriever: candidate counts, latency p50/p99, error rate, and — the metric that matters — which side supplied the winning fused result (the retriever(s) containing the top-1 doc). A healthy hybrid shows both sides contributing; if lexical wins 0.1% of queries for a month, either your corpus has no exact-term traffic (drop it) or the lexical index is broken (fix it). Alert on fusion-input anomalies: empty candidate sets, ID-format mismatches (fused score == single-side max everywhere), sudden weight of one side → 1.0.
Failure gallery#
| What you see | Likely cause | Fix |
|---|---|---|
| Fused top-1 is always from one retriever | weights degenerate, or one side returns empty | check per-side candidate counts; verify ID formats match |
| Good docs ranked ~k+1, never surfaced | k_dense/k_lex too small; rank_window_size default 10 in ES |
over-fetch (30–100/side); set window/prefetch limits explicitly |
| Results differ between page 1 and page 2 | paginating each retriever separately | fuse deep, paginate the fused list (4.4) |
| Hybrid recall worse than dense-only | lexical side injecting noise at weight too high; or ID mismatch splitting votes | lower lexical weight; audit ID normalisation |
| Score fusion ranks weirdly per query | min-max/z-score stats computed on tiny per-query top-k; outlier collapse | switch to RRF, or DBSF; increase candidate depth |
| "alpha=0.5" behaves like alpha=0.9 | alpha convention differs per engine (Pinecone: α weights dense; Redis COMBINE LINEAR has separate ALPHA/BETA) |
read the vendor's convention; test extremes |
| After re-embedding, lexical results look stale | indexes cut over at different times; IDF drift | generation-tagged indexes, atomic cutover (9.2) |
| One retriever down → results silently dense-only | no degradation policy / no alerting | explicit fallback + per-mode logging (4.3) |
| Duplicate-ish chunks fill top-5 | adjacent chunks of one doc all fuse high | group-by-document dedupe or reranker diversity (4.2) |
| Identifier queries still miss | lexical analyser splits VPN-ERR-2041 into pieces or drops it |
keyword-aware tokenisation / n-gram field (06.7) |
| Tune/val gap: tuned weights fail in prod | tuned on same queries measured; toy eval set too small | split-half tuning; hundreds of queries (5.3) |
Decision table#
| Situation | Recommended fusion | Why |
|---|---|---|
| No eval set, first hybrid deployment | RRF, equal weights, engine default k | only config with published robustness evidence |
| Eval set exists, retrievers' scores trustworthy | weighted RRF or DBSF tuned on train split | keeps magnitude info; tune on held-out data |
| Scores carry calibrated margins, large eval set | learned fusion / LTR | ceiling, but needs data + maintenance |
| Multi-collection / multi-tenant shards | RRF | scores incomparable across collections by construction |
| Display-layer merge (tabs, federated UI) | interleave/round-robin | fairness, not relevance |
| Identifier-heavy traffic | route to lexical or lexical-heavy weights | dense is structurally blind to exact strings |
| One engine available (pgvector+FTS, single DB) | SQL RRF or client RRF | avoids dual-write entirely |
| Latency-critical, one retriever suffices | dense-only or lexical-only | hybrid's cost isn't justified by eval |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Hybrid always beats either retriever alone." | Not on every dataset — our toy eval had lexical-only beating dense-only. Measure (1.2, Part 7). |
| "You can add BM25 and cosine scores with an alpha." | Only after normalisation — raw scales are incomparable and shift per query (2.1). |
| "RRF's k=60 is magic." | It was fixed in a pilot and insensitive across 10–100; Qdrant defaults to k=2 for its own reasons. Set it explicitly (2.2). |
| "alpha means the same thing everywhere." | Pinecone α=1 = pure dense; check each vendor's convention (3.3). |
"Postgres ts_rank is BM25." |
It isn't — it's Postgres's own ranking function; BM25 needs an extension (3.8, 06.7). |
| "Fuse first, filter later." | Filters belong inside each retriever's candidate generation — post-filtering the fused list reintroduces recall collapse (4.2, 06.6). |
| "Two indexes stay in sync automatically." | They don't — that's the main operational cost of DIY hybrid (9.1). |
| "Tuning weights on your eval set and reporting that number is fine." | It's inflated — split tune/validation (5.3). |
| "Reranking fixes bad fusion." | Rerankers only see the fused candidates — starve them and there's nothing to rerank (1.3). |
Key takeaways#
- Hybrid combines complementary blind spots: dense misses exact identifiers and rare terms; lexical misses paraphrase and synonyms. Evidence it helps is strong but dataset-dependent — ablate before adopting.
- Scores are incomparable across retrievers — every fusion method is an answer to that: RRF/Borda discard scores for ranks; score fusion normalises (min-max, z-score, arctan); DBSF normalises by distribution; interleaving ignores scores entirely.
- RRF is the safe default:
Σ w_r/(k + rank), k=60 from the 2009 SIGIR paper (Qdrant uses k=2; Elasticsearch/OpenSearch/LanceDB/Chroma default 60). Weighted RRF is how you tilt toward one side. - Most engines have native hybrid — Elasticsearch/OpenSearch retrievers+pipelines, Qdrant prefetch+fusion, Pinecone alpha/RRF, Chroma
Rrf, LanceDBRRFReranker, Redis 8.4+FT.HYBRID, and DIY SQL for pgvector+FTS, sqlite-vec and DuckDB (FAISS and S3 Vectors need a second retriever). Defaults differ (k2 vs 60, window 10 vs 20, alpha direction), so set them explicitly. - No labelled data: RRF. A small labelled set: also try a tuned convex combination (Bruch et al. 2023 found it beat RRF and needed few examples) — and let your own eval decide.
- Candidate depth, dedup by doc, ID consistency and parallel execution matter as much as the fusion formula.
- Tune on a labelled set with a train/validation split; without one, leave weights equal.
- Two indexes must stay consistent — prefer one engine doing both representations; otherwise version and cut over atomically.
- Reranking is the next stage (06.9) and evaluation methodology is 06.10; this lesson stops at a fused, ranked candidate list.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Dense retrieval | Retrieval that ranks documents by embedding similarity — a query vector and document vectors compared in a shared vector space — as opposed to lexical/keyword retrieval, which matches terms; the two are complementary and combined in hybrid search |
| Hybrid search | Retrieval that combines lexical (BM25/FTS) and dense (embedding) rankings into one result list |
| Fusion | The stage that merges multiple retrievers' ranked lists into a single ranking |
| Reciprocal Rank Fusion (RRF) | Rank-based fusion: score(d) = Σ 1/(k + rank_r(d)); k=60 in the original paper |
| Weighted RRF | RRF with a per-retriever multiplier on each contribution |
| Borda count | Position-based fusion awarding N − rank + 1 points per list (linear decay) |
| Score fusion | Weighted sum of per-retriever normalised scores (min-max or z-score) |
| CombSUM / CombMNZ / CombMAX | Classic metasearch fusion family (Fox & Shaw 1994): sum of scores, sum × number of lists containing the doc, and max — all assume comparable score scales |
| DBSF | Distribution-Based Score Fusion (Qdrant): normalise by mean ± 3σ, then sum |
| Relative score fusion | Min-max-normalised weighted score fusion (Elasticsearch linear with minmax) |
| Interleaving | Round-robin merge of ranked lists with no scores |
| Learning-to-rank | Supervised fusion: a model scores (query, doc) pairs using retrieval features |
| Candidate set | The top-k hits each retriever returns before fusion |
| Query routing | Choosing retriever weights (or bypassing fusion) by query type |
| Ablation | Comparing BM25-only, dense-only and hybrid on the same eval set |
| Convex combination | Score fusion with a single weight, α·dense + (1−α)·lexical, over normalised scores; Bruch et al. (2023) found it beat RRF when tuned on a few labelled queries |
rank_window_size / WINDOW |
The per-retriever depth an engine (Elasticsearch, Redis) feeds into RRF; a too-small default silently truncates each list before fusion |
| Dual-write | Writing each chunk to two indexes; the consistency burden of DIY hybrid |
Exercises#
- Fusion by hand (2.2): compute the RRF(k=60) score for
contract-9indemo_fusion.py's three rankings (ranks 5, 3, 4 — dense, BM25, sparse) and verify it matches the printed 0.0469. - Extend
fusion.py: addmean_reciprocal_rankfusion (average of1/rankwithout the k offset) and compare its output on the demo rankings to RRF k=10 — when do they diverge? - Weight sweep (5.3): extend
tune.pyto sweeprrfweights over a grid[(w, 1-w) for w in [0.1..0.9]]on the labelled set; plot recall@5 vs w. With only 7 queries, how noisy is the optimum? - Router (5.2): write
route(query: str) -> tuple[float, float]returning (dense_w, lex_w) that sends queries containingERR-,INV-, or all-caps tokens to lexical-heavy fusion. Test it on the three demo queries. - Degradation (4.3):
resilient.pyonly covers the async path. Port the same idea to the synchronousHybridRetriever.search(catch each retriever's exception, fuse the survivors, returnserved_by), and makeFlakyRetrieverfail on every second call. What should the fused score mean when only one side answered, and what would you put in the log line? - SQL (3.8): rewrite
hybrid_rrf.sqlfor three ranked CTEs (dense, tsvector, pg_trgm similarity) using twoFULL OUTER JOINs — or aUNION ALLof per-side(id, rrf_part)rows grouped by id, whichever is clearer. - Ablation (Part 7):
tune.pyalready printsdense onlyandlexical onlyrows next to the fused configs. Following the four-step procedure in Part 7, argue from that table whether hybrid earns its keep on this corpus (does it beat both singles by more than the noise?) — then add three queries of your own that need an exact identifier and three that are pure paraphrase, re-run, and explain why the answer would differ at 100k chunks. - Monitoring (9.4): sketch the log event you'd emit per query to compute "which side supplied the winner" — fields, where it's emitted, and the alert you'd set on a 7-day lexical-win-rate below 1%.
Hints and what you should see
1/65 + 1/63 + 1/64 = 0.015385 + 0.015873 + 0.015625 = 0.046883, which rounds to the printed0.0469. Dense rank 5 iscontract-9(0.31), BM25 rank 3 (7.1), sparse rank 4 (0.96).- Define
mrr_fusion(rankings)asscore[d] += 1/rank(that isrrfwithk=0). On the demo lists it giveshandbook-0012.0,help-101andticket-781.5833 each,handbook-0020.8667,contract-90.7833. RRF with k=10 givescontract-90.2150 abovehandbook-0020.2125 — the two flip. Reason: with no offset the rank-1 contribution is twice rank-2's and 5x rank-5's, so a doc that is #2 on one list outweighs a doc that is mediocre on three;k=10flattens that just enough to reward consistency. The orderings only diverge where one doc has a very good rank in one list and the other is steadier. - Wrap the loop in
for w in [0.1, ..., 0.9]withlambda rs, w=w: rrf(rs, k=60.0, weights=[w, 1 - w])(bindwas a default argument, or every lambda sees the lastw). Expected MRR@5: 0.929 at w=0.1, 1.000 at 0.2 to 0.4, 0.929 at 0.5 to 0.7, 0.857 at 0.8 and 0.9; recall@5 stays 1.0 throughout. With seven queries one query moving from rank 2 to rank 1 shifts MRR by about 0.07, so the "optimum" 0.2–0.4 is a plateau you cannot distinguish from noise — the lesson of 06.10's confidence intervals. - A pure function is enough:
if re.search(r"\b[A-Z]{2,}-\d+|\bINV-|\bERR-", query): return (0.3, 0.7);if len(query.split()) <= 3: return (0.4, 0.6); else(0.7, 0.3)(dense weight first, matchingrrf(..., weights=[dense, lexical])). On the demo queries onlywhat is error code VPN-ERR-2041?matches the identifier pattern and goes lexical-heavy(0.3, 0.7); the invoice and vacation questions fall through to(0.7, 0.3)(the invoice query has no code in it — a router based onINV-would only fire forINV-2042-style text). Test withassert route(...), no retriever needed. - Catch exceptions per retriever (
try/except Exceptionaround eachr.search), append to afailedlist, and raise only when no retriever answered. With one survivor RRF returns that retriever's order with scores1/(k+rank); those scores are not comparable to healthy-mode scores, so logserved_byand never threshold on fused RRF scores across modes. - Add
trigram AS (SELECT id, similarity(content, %(qtext)s) AS s FROM handbook_chunks WHERE content %% %(qtext)s ORDER BY s DESC LIMIT %(k_lex)s)(needsCREATE EXTENSION pg_trgm), rank it withROW_NUMBER(), then either join twice withFULL OUTER JOIN(the second join must key onCOALESCE(d.id, l.id)) orUNION ALLthree(id, 1.0/(k + r))selects andGROUP BY idwithSUM— theUNION ALLform is shorter and scales to N lists. - Expected from the 5.3 table: every row has recall@5 = 1.0; MRR is 0.786 dense, 0.929 lexical, 0.929 for equal-weight RRF — so hybrid ties the best single retriever and wins only with a tuned weight on seven queries. By Part 7's rule that is not yet evidence for hybrid. At 100k chunks recall@5 stops saturating, the dense retriever's blind spot on identifiers and the lexical retriever's on paraphrase both cost real queries, and the gap between hybrid and the best single retriever becomes measurable.
- One structured event per query, emitted by the fusion stage:
query_id,served_by(list), per-siden_candidatesandlatency_ms,top1_id,top1_from(dense,lexicalorboth) and the fused weights. Aggregatetop1_fromper day; alert when the 7-day share oflexicalwins (includingboth) is below 1%, then check whether the lexical index is empty or stale before concluding the corpus has no exact-term traffic.
Check yourself#
- Why can't you add a BM25 score and a cosine score directly?The scores live on different, query-dependent scales — BM25 is unbounded and its magnitude shifts with corpus statistics; cosine is bounded. Adding them lets whichever scale is larger dominate (2.1).
- What does the
kin RRF control, what value did the original paper use, and why might an engine choose a different default?ksmooths the top of each list — higher k flattens rank differences (rank 1 vs 60 matter less). The 2009 SIGIR paper fixed k=60 in a pilot and found MAP insensitive over 10–100. Engines differ because their candidate depths differ — Qdrant defaults k=2 for small prefetch top-k; others follow the paper (2.2). - What's the difference between RRF and Borda count in how they treat rank positions?
- When would you prefer score fusion (min-max/z-score) over RRF, and what's its main fragility?When retrievers' raw scores carry trustworthy magnitude information you want to preserve (confident-vs-barely-ahead distinctions). Fragility: normalisation stats are computed per query over a small top-k, so one outlier compresses or skews the whole list (2.3).
- What is DBSF, and which engine implements it?Distribution-Based Score Fusion — Qdrant's v1.11+ method: per retriever, map scores by
(s − (μ−3σ))/6σthen sum; not clipped, degenerate input → 0.5 (2.5). - In Pinecone's single-index hybrid, what do
α=0andα=1mean, and where is the scaling applied?α=1is pure dense,α=0is pure sparse; you scale the query vectors client-side (α·dense,(1−α)·sparse) before the request (3.3). - Why does Qdrant default RRF to
k=2, and how do Qdrant's weights differ from Elasticsearch's?With a prefetch depth around 20,k=60makes every contribution nearly equal, so Qdrant pickedk=2; its weights scale rank position, while Elasticsearch'sweightmultiplies the contribution (3.2). - What's wrong with paginating each retriever separately and merging pages?Each retriever's page boundaries differ — page 2 re-shows page-1 hits and misses docs that only ranked well in fusion. Fuse deep, then paginate the fused list (4.4).
- Name three ways to keep dense and lexical indexes consistent, and the trade-off of each.One engine holding both representations (simplest, one consistency domain); dual-write via transactional outbox (flexible, you own ordering/retries); single source of truth + versioned atomic index cutover (safest, most rebuild cost) (9.1).
- Your hybrid system returns dense-only results after a deploy — what are the three most likely causes?The lexical retriever threw and you degraded silently; its index/credentials broke after deploy; or ID formats changed so fusion sees disjoint sets (4.3, failure gallery).
- Why is a
FULL OUTER JOIN(notINNER JOIN) needed in the SQL RRF pattern?Docs present on only one side still earn1/(k+rank)from that side — an inner join would drop them (3.8). - When is hybrid search not worth it? Give two concrete conditions.Tiny corpora where dense brute-force already saturates recall; query logs showing no exact-term traffic; eval sets where one retriever already hits recall@10 ≈ 1.0; hard latency/cost budgets (Part 7).
- What does "which side supplied the winning result" monitoring tell you that aggregate recall doesn't?It shows whether both retrievers earn their keep — a side winning ~0% of queries means drop it or fix it; aggregate recall can't distinguish "both contributed" from "one did all the work" (9.4).
- A colleague sets
rank_window_sizeto the default 10 but fetches top-50 per side expecting deep fusion. What happens?rank_window_sizetruncates each child's list before fusion — your effective per-side depth is 10, not 50; the extra candidates never reach the RRF formula (3.1). - Why should fusion weights be tuned on a train split and measured on a validation split?Tuning and measuring on the same queries inflates the tuned config's score (overfitting the eval set); a validation split estimates true performance (5.3).
Further resources#
- Cormack, Clarke & Büttcher, "Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods" — the 2009 SIGIR paper; k=60 origin.
- Elasticsearch, RRF retriever, reciprocal rank fusion and linear retriever — parameters, weighted retrievers, normalisers.
- OpenSearch, Hybrid search and score ranker processor —
hybridquery, RRF pipeline, weights. - Qdrant, Hybrid and Multi-Stage Queries — prefetch/fusion, RRF vs DBSF formulas, weight-tuning guidance.
- Pinecone, Hybrid search overview and single-index hybrid — alpha scaling, RRF patterns.
- Chroma, Hybrid Search with RRF —
Search/Knn/RrfAPI. - LanceDB, Reranking, RRFReranker and hybrid search.
- Bruch, Gai & Ingber, An Analysis of Fusion Functions for Hybrid Retrieval — convex combination vs RRF, sensitivity and sample efficiency. Thakur et al., BEIR — BM25 as a robust zero-shot baseline.
- Redis,
FT.HYBRID; sqlite-vec, vec0 KNN with SQLite FTS5; DuckDB, VSS and full-text search; AWS, S3 Vectors. - PostgreSQL,
ts_rank/ts_rank_cdandwebsearch_to_tsquery— the FTS side of the SQL pattern.
← 06.7 — Keyword Search and BM25 | Module 06 overview | 06.9 — Reranking →