Hybrid Search from First Principles: BM25, Vectors and Where Rank Fusion Buries an Exact Match
A dependency-free hybrid retriever in about 200 lines of Python: BM25 over an inverted index, a flat cosine index, and reciprocal rank fusion, measured on a labelled fixture. The numbers show where each arm is blind and where default RRF buries an exact match.

A support engineer pastes E-4021 into the search box of a knowledge base and the embedding retriever answers with the page about API versioning. A customer writes "we keep getting throttled" and the keyword retriever answers with the same page, because the only word the query shares with the corpus is "keep". Both results come from the fixture built for this article, and both are the retriever working as designed. Each method has a class of query it cannot see.
Hybrid search with BM25 and vector retrieval exists because those two blind spots barely overlap. The interesting engineering is in the step that joins the arms, where two score scales with nothing in common have to produce one ranking. This article implements every stage in plain Python with no search library: BM25, a vector index, reciprocal rank fusion (RRF), and a measurement of each arm on 32 labelled queries. The measurement also turns up a case that the default settings hide, where RRF pushes a correct first-place result down to sixth.
Two retrievers, two blind spots
Lexical retrieval scores a document by the query terms it literally contains. It is exact on identifiers such as error codes, configuration keys and header names, and it finds nothing when the user describes a problem in words the documentation does not use. Dense retrieval embeds query and document into one vector space and ranks by distance. It matches meaning across different wording, and it is weak on rare strings, because an identifier the encoder has hardly seen is broken into sub-word pieces that many other identifiers share. How an embedding comes out of a language model is covered elsewhere; what matters here is that behaviour.
The fixture makes the difference concrete. It is a knowledge base of 36 short entries for a fictional payments API and 32 queries in four classes:
| Query class | Example | What it stresses |
|---|---|---|
| identifier | idempotency_ttl | An exact string that occurs in one or two entries |
| paraphrase | "terminate a recurring membership" | Meaning with no shared key terms |
| mixed | "shopper abandoned the bank otp E-4310" | Both signals at once |
| plain | "how long does a refund take to appear" | Ordinary questions with partial overlap |
BM25 in fifty lines
BM25 is a term-weighting function with three ideas in it: rare terms count more (inverse document frequency), repeated terms count more but with diminishing returns (saturation, controlled by k1), and long documents are discounted (length normalisation, controlled by b).
def tokenize(text: str) -> list[str]: """Lower-case word tokens. A compound such as `E-4012` or `webhook.max_retries` is kept whole AND emitted as its parts, so both the exact identifier and its pieces are searchable.""" out: list[str] = [] for tok in TOKEN.findall(text.lower()): out.append(tok) parts = re.split(r"[-_.]", tok) if len(parts) > 1: out.extend(parts) return out class BM25: def __init__(self, docs: dict[str, str], k1: float = 1.2, b: float = 0.75): self.k1, self.b = k1, b self.postings: dict[str, dict[str, int]] = defaultdict(dict) # term -> {doc_id: tf} self.length: dict[str, int] = {} for doc_id, text in docs.items(): terms = tokenize(text) self.length[doc_id] = len(terms) for term, tf in Counter(terms).items(): self.postings[term][doc_id] = tf self.n = len(docs) self.avgdl = sum(self.length.values()) / max(self.n, 1) def idf(self, term: str) -> float: # The "+ 1" inside the log keeps IDF positive for terms that occur in more # than half of the documents; the original formula goes negative there. df = len(self.postings.get(term, ())) return math.log(1 + (self.n - df + 0.5) / (df + 0.5)) def search(self, query: str, k: int = 10) -> list[tuple[str, float]]: scores: dict[str, float] = defaultdict(float) for term in dict.fromkeys(tokenize(query)): # unique terms, query order idf = self.idf(term) for doc_id, tf in self.postings.get(term, {}).items(): norm = 1 - self.b + self.b * self.length[doc_id] / self.avgdl scores[doc_id] += idf * tf * (self.k1 + 1) / (tf + self.k1 * norm) # Documents that share no term with the query are absent, not scored zero. return sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))[:k]
Four decisions in this listing change results more than the formula does.
The tokeniser keeps a compound such as webhook.max_retries as one token and also emits its parts. Keeping it whole is what makes an identifier query exact. Emitting the parts lets "max retries" find the same entry. The cost appears later: E-4021 also emits the token e, which matches every error page in the corpus.
The IDF has 1 + inside the logarithm. The classic Robertson–Spärck Jones form, log((N - df + 0.5) / (df + 0.5)), is negative for any term that occurs in more than half of the documents, so a match on a common word would lower a score. A test in the suite pins both facts.
k1 = 1.2 and b = 0.75 are conventional starting values. Robertson and Zaragoza report that k1 between 1.2 and 2 and b between 0.5 and 0.8 work reasonably in many collections, and they are explicit that the best values depend on the documents.
The last line of search returns only documents that share a term with the query. An inverted index never visits the others, so the lexical arm can return fewer than k results, or none. That asymmetry with the dense arm matters in the fusion step.
There is no stemming. "webhooks" and "webhook" are different terms here, which is why the query "how are webhooks retried" ranks the right entry third in this arm. A production analyser would stem; the omission keeps the example readable and leaves one more lexical failure in the measurements.
A vector index, with a declared stand-in for the encoder
A real embedding model cannot be shipped in a small, deterministic example, so this one uses a stand-in and says so. A hand-written table maps words with the same meaning to one direction in a 64-dimensional space ("refund", "reimbursement" and "repaid" share a vector). Any token outside the table is broken into character trigrams with a small weight. That reproduces the two properties that decide hybrid behaviour: synonyms land together, and E-4012 and E-4021 land close to each other (cosine 0.53 in the test suite) because they share most of their pieces. It reproduces nothing else about a trained encoder, and no number below says anything about a specific model. The paraphrase queries were also written with that table in view, so the dense arm's strength on them is built in. The fixture is there to expose what fusion does with two lists of known quality, not to compare the arms.
def embed(text: str) -> list[float]: vec = [0.0] * DIM for tok in TOKEN.findall(text.lower()): if tok in STOPWORDS: continue concept = WORD_TO_CONCEPT.get(tok) if concept is not None: pieces, weight = [f"concept:{concept}"], 1.0 else: # character trigrams, the toy version of sub-word tokenisation padded = f"^{tok}$" pieces = [f"tri:{padded[i:i + 3]}" for i in range(len(padded) - 2)] weight = OOV_WEIGHT / len(pieces) for piece in pieces: for i, x in enumerate(_unit(piece)): vec[i] += weight * x return _normalise(vec) # weighted sum pooling; L2 normalisation removes the scale class VectorIndex: def __init__(self, docs: dict[str, str]): self.vectors = {doc_id: embed(text) for doc_id, text in docs.items()} def search(self, query: str, k: int = 10) -> list[tuple[str, float]]: q = embed(query) scored = [(doc_id, sum(a * b for a, b in zip(q, v))) for doc_id, v in self.vectors.items()] # Every document gets a score. Nearest-neighbour search always returns k # results, however far away the nearest neighbour is. return sorted(scored, key=lambda kv: (-kv[1], kv[0]))[:k]
The index is flat: every query is compared with every vector, which is exact and is the baseline that approximate indexes such as HNSW trade away for speed. The comment in search is the important line. A nearest-neighbour search has no notion of "no match". For the query E-4021 the best cosine in the corpus is 0.22, and the index still returns twenty results in a confident order.
Hybrid search with BM25 and vector scores: why adding them fails
The obvious way to combine the arms is to add their scores. For E-4021, BM25 gives the correct entry 9.40 and the runner-up 5.76, while the dense arm's best score is 0.22. BM25 scores are unbounded sums that grow with the number of query terms and shift whenever the corpus statistics change; cosine similarity lives in [-1, 1]. A plain sum is the lexical ranking with the dense score as a tie-breaker.
The usual repair is to rescale each list to [0, 1] with min-max normalisation and take a weighted sum. That works better, and on this fixture it performs well. It also makes the fused order depend on things that have nothing to do with relevance: the minimum of each list moves with how many candidates were requested, and one outlier at the top compresses everything beneath it.
Reciprocal rank fusion discards the scores and keeps only the positions:
def rrf(rankings: Sequence[Sequence[str]], k: int = 60, weights: Sequence[float] | None = None) -> list[tuple[str, float]]: """Fuse ranked lists of document ids. Only positions are read, never scores. score(d) = sum over lists of weight / (k + rank of d in that list), rank from 1. A document missing from a list contributes nothing for that list. """ weights = weights or [1.0] * len(rankings) fused: dict[str, float] = defaultdict(float) for ranking, weight in zip(rankings, weights): for rank, doc_id in enumerate(ranking, start=1): fused[doc_id] += weight / (k + rank) # Exact ties are common: ranks (3, 5) and (5, 3) give the same sum. Break them # on the id so that the order never depends on dict iteration. return sorted(fused.items(), key=lambda kv: (-kv[1], kv[0]))
A document's fused score is the sum of 1 / (k + rank) over the lists that contain it. Since scores never enter, there is nothing to normalise, and the property can be stated as a test rather than as an opinion. Applying any order-preserving transformation to one arm's scores must leave the RRF result untouched and is free to change a score-based fusion:
def test_rrf_ignores_any_order_preserving_change_of_scores_but_score_fusion_does_not(): docs = load_docs() lexical, dense = BM25(docs), VectorIndex(docs) query = "how long does a refund take to appear" lex, den = lexical.search(query, 20), dense.search(query, 20) squashed = [(d, math.log1p(s)) for d, s in lex] # same order, different scale assert [d for d, _ in squashed] == [d for d, _ in lex] ids = lambda hits: [d for d, _ in hits] assert rrf([ids(squashed), ids(den)]) == rrf([ids(lex), ids(den)]) assert ids(convex(squashed, den)) != ids(convex(lex, den)) assert ids(raw_sum(squashed, den)) != ids(raw_sum(lex, den))
This is the real argument for RRF in a system that will change. Swap the embedding model, change BM25's k1, move from cosine to inner product: each of these rescales one arm, and none of them can alter the fused ranking unless it alters that arm's order.
Figure 1. The two arms run independently and meet only as ranked lists; no score reaches the fusion step.
The constant k comes from the paper that introduced the method. Cormack, Clarke and Buettcher fixed k = 60 in a pilot study, observed that results were stable across a wide range, and described its role as limiting the influence of high rankings by outlier systems. With k = 60, first place is worth 1/61 and twentieth place 1/80: the top of a list is worth only about 30% more than the bottom. That flatness is deliberate, and it has a consequence.
Figure 2. The same formula on two fixture queries. Agreement between the lists helps the first and buries the second.
What each arm scored on the fixture
evaluate.py runs every arm on every query with a candidate depth of 20 and reports recall@5 and mean reciprocal rank. These are measurements on a 36-entry fixture with a toy encoder. They show mechanisms and are not a benchmark of any real system.
recall_at_5 (32 queries, 36 documents) arm identifier paraphrase mixed plain all bm25 1.000 0.625 1.000 1.000 0.906 vector 0.125 1.000 1.000 1.000 0.781 raw_sum 1.000 0.875 1.000 1.000 0.969 convex 1.000 0.875 1.000 1.000 0.969 rrf 0.875 1.000 1.000 1.000 0.969 rrf+floor 1.000 0.875 1.000 1.000 0.969 mrr_at_10 (32 queries, 36 documents) arm identifier paraphrase mixed plain all bm25 1.000 0.268 1.000 0.854 0.781 vector 0.070 0.844 0.792 1.000 0.676 raw_sum 1.000 0.556 1.000 0.875 0.858 convex 0.938 0.701 1.000 1.000 0.910 rrf 0.594 0.719 1.000 1.000 0.828 rrf+floor 0.938 0.812 1.000 1.000 0.938
The first two rows are the reason hybrid retrieval exists. BM25 is perfect on identifiers and finds the right entry in the top five for 62.5% of paraphrases, usually low in the list. The dense arm is the mirror image. On mixed and plain queries either arm alone is enough, which is a reminder that most of the value of fusion is concentrated in the minority of queries where one arm has nothing.
The rrf row is less comfortable. Overall recall rises to 0.969, as expected. But on identifier queries, where BM25 alone had a reciprocal rank of 1.000, RRF scores 0.594. Fusion took results that were already correct and made them worse.
Figure 3. Mean reciprocal rank per query class on the fixture. Default RRF pays for its paraphrase gain on identifier queries.
Consensus beats excellence: the failure the defaults hide
The trace for E-4021 shows the mechanism. The correct entry, kb-02, is first in BM25 and absent from the dense top 20.
query: 'E-4021' k=60 depth=20 dense_floor=None rank doc bm25 vector 1/(k+r) bm25 1/(k+r) vec rrf 1 kb-33 3 2 0.0159 0.0161 0.0320 2 kb-03 4 12 0.0156 0.0139 0.0295 3 kb-18 8 11 0.0147 0.0141 0.0288 4 kb-25 9 10 0.0145 0.0143 0.0288 5 kb-01 6 14 0.0152 0.0135 0.0287 6 kb-02 1 - 0.0164 - 0.0164
Five entries that are mediocre in both lists beat the one that is first in a single list. This is arithmetic, and it is general. With two lists of depth n, the weakest document that appears in both scores 2 / (k + n). The strongest document that appears in only one scores 1 / (k + 1). The first exceeds the second whenever n < k + 2. At k = 60, any candidate depth up to 61 guarantees that a document found by both arms outranks a document found by one, however good that one placement is.
That is a sensible rule when both lists carry signal. It is the wrong rule when one arm is guessing, and the dense arm always produces a full list. The other error pages reach the BM25 list through the token e that the tokeniser emitted, they reach the dense list because neighbouring codes share trigrams, and two weak votes outweigh one strong one.
Three repairs are available, and the sweep in sweep.py measures each on the fixture:
configuration R@5 id MRR id R@5 para MRR para R@5 all MRR all k=1 depth=20 floor=- 1.000 0.875 0.875 0.688 0.969 0.891 k=60 depth=10 floor=- 1.000 0.677 1.000 0.681 1.000 0.840 k=60 depth=20 floor=- 0.875 0.594 1.000 0.719 0.969 0.828 k=60 depth=20 floor=0.2 1.000 0.812 1.000 0.792 1.000 0.901 k=60 depth=20 floor=0.3 1.000 0.938 0.875 0.812 0.969 0.938 k=60 depth=20 floor=0.4 1.000 1.000 0.875 0.825 0.969 0.956
A smaller k makes the formula top-heavy, so a first place can stand on its own. At k = 1 identifier MRR recovers to 0.875 and paraphrase recall drops, because the same top-heaviness now lets a wrong lexical first place win.
A shallower candidate depth removes weak votes from both arms. It helped here and is not a principled control: it also removes the deep candidates that fusion exists to rescue.
Letting an arm abstain addresses the cause. BM25 already abstains, since it returns nothing when no term matches. Giving the dense arm the same ability, by dropping hits below a similarity floor before fusion, restores identifier ranking while keeping most of the paraphrase gain.
class HybridRetriever: def __init__(self, docs: dict[str, str], depth: int = 20, k_rrf: int = 60, dense_floor: float | None = None): self.lexical = BM25(docs) self.dense = VectorIndex(docs) self.depth = depth # candidates each arm may contribute self.k_rrf = k_rrf self.dense_floor = dense_floor # cosine below which the dense arm abstains def arms(self, query: str) -> tuple[list[str], list[str]]: lexical = [doc_id for doc_id, _ in self.lexical.search(query, self.depth)] dense = [doc_id for doc_id, score in self.dense.search(query, self.depth) if self.dense_floor is None or score >= self.dense_floor] return lexical, dense def search(self, query: str, k: int = 5) -> list[tuple[str, float]]: return rrf(self.arms(query), k=self.k_rrf)[:k]
The floor is a score threshold, which looks like a retreat from the whole argument for rank fusion. It is not, because it compares a dense score only with other dense scores from the same model, where the scale is consistent. What RRF forbids is comparing scores across arms. The floor still has to be calibrated per embedding model on labelled queries, since real encoders have very different similarity distributions, and it has a price that the table shows: at 0.3 one paraphrase query loses its only dense evidence and falls out of the top five. The 0.3 used in the rrf+floor row was chosen by looking at this same fixture, so that row is an optimistic estimate.
One more honest reading of the numbers: the min-max convex combination has a higher overall MRR (0.910) than default RRF (0.828) on this fixture. That agrees with Bruch, Gai and Ingber, who found that a convex combination outperformed RRF in their experiments and that RRF is more sensitive to its parameters than commonly assumed. RRF's advantage is that it needs no labelled data and survives changes to either arm. With a labelled set and stable arms, a tuned score fusion is a legitimate choice.
From 200 lines to a database
In production the two arms are usually indexes in a search engine or a database, and the fusion step is a query. The fusion logic above is small enough to write in SQL:
-- Reciprocal rank fusion of two candidate lists. -- lexical(doc_id, rank) and dense(doc_id, rank) hold each arm's top-N, rank from 1. -- A document missing from one arm gets no contribution from it (COALESCE to 0). SELECT COALESCE(l.doc_id, d.doc_id) AS doc_id, COALESCE(1.0 / (:k + l.rank), 0.0) + COALESCE(1.0 / (:k + d.rank), 0.0) AS score FROM lexical AS l FULL OUTER JOIN dense AS d ON d.doc_id = l.doc_id ORDER BY score DESC, doc_id LIMIT :top;
The test suite executes this statement on SQLite for all 32 fixture queries and checks that it returns the same order and scores as the Python function. The parts that would feed it in PostgreSQL, a full-text CTE and a pgvector CTE, were not executed for this article, and three documented facts about them deserve attention before trusting such a setup.
PostgreSQL's built-in ts_rank and ts_rank_cd are not BM25. The documentation states that these functions use no global information, which means no inverse document frequency: a match on a rare error code and a match on a common word are weighted alike. Rank fusion tolerates a mediocre scorer better than score fusion does, since only order matters, but an arm with no IDF will order identifier queries worse than the BM25 shown here.
pgvector performs exact search by default and switches to approximate search when an HNSW or IVFFlat index is added, trading recall for speed. The candidate list entering fusion is then itself approximate, and its recall is a tunable to measure separately. General indexing trade-offs in relational databases apply to both arms.
Elasticsearch exposes the same two knobs measured above under the names rank_constant (default 60) and rank_window_size. Its reference describes RRF as requiring no tuning. The fixture results suggest reading that as "no tuning needed to get a reasonable result", not as "the defaults cannot hurt".
Four operational points follow from the architecture and not from any product:
- Run the arms concurrently. They are independent, so latency is the slower arm plus fusion, not the sum.
- Apply the same filter to both arms. A tenant or permission filter present in one arm and missing in the other lets the unfiltered arm inject documents the caller may not see, and fusion will rank them.
- Keep the indexes in step. A document that has reached the lexical index but not yet the vector index can only ever earn half of the possible score. During ingestion lag, new documents are systematically under-ranked.
- Log ranks per arm. The
explain.pytrace above is the single most useful debugging artefact. Without per-arm ranks, a bad fused result cannot be attributed.
When the retriever is exposed to a model as a tool, as in the agent loop built in the first article of this series, the same trace belongs in the tool's logs, and the result should say how many candidates each arm contributed.
Testing and what was verified
The suite has 27 tests in four groups. The BM25 tests compare a score with a value computed by hand from the formula, check that IDF stays positive, and check that a query with no matching term returns an empty list. The vector tests assert unit length, that synonyms coincide, and that the embedding is byte-identical in a second process started with a different PYTHONHASHSEED. That test exists because Python's built-in hash is salted per process: an embedding seeded from it would produce a different index on every run, so the code derives its seeds from hashlib. The fusion tests cover a worked example with exact fractions, deterministic tie-breaking, weights, the invariance property and the consensus inequality at three settings of k and depth. The fixture tests pin the measured pattern, including the identifier regression, so a change that silently alters it fails.
Pinning a disappointing number in a test is intentional. A test that asserts "default RRF demotes exact identifier hits on this fixture" documents a known limit and fails the day someone fixes it or breaks it differently.
Verification. All 27 tests pass on Python 3.13.18 with pytest 9.2.0 (November 2026); evaluate.py and sweep.py produced the tables quoted above, and the SQL statement was executed on SQLite 3.53.1. Nothing here was run against a trained embedding model, an approximate index, PostgreSQL with pgvector, or Elasticsearch; statements about those systems come from their documentation. The fixture is small and was written for this article, so its numbers illustrate mechanisms and do not predict results on other corpora. A retrieval change should be judged on a labelled set drawn from real queries, and skipping that measurement is one of the recurring reasons AI features fail after launch.
Common mistakes
Adding raw scores. The arm with the larger numeric range wins, and which arm that is changes with corpus size and query length.
Treating RRF as tuning-free. k and candidate depth interact; with depth at most k + 1, agreement always beats a single first place.
Letting an arm vote when it has no evidence. A nearest-neighbour index returns k results for any input. Without a floor or a query router, its noise is fused as if it were signal.
Evaluating only the average. The overall recall of default RRF and of RRF with a floor is identical here, 0.969. The difference is visible only per query class.
Splitting identifiers without keeping them whole. A tokeniser that turns E-4021 into e and 4021 alone makes every error page a match for every error code.
Fusing lists produced under different filters. The fused list is only as access-controlled as its least filtered arm.
Engineering verdict
Use hybrid retrieval when the queries a system receives include both exact strings and free descriptions. Support search, code and API documentation, product catalogues with part numbers, and legal or clinical text with coded identifiers all fit. Start with RRF, because it needs no labels and survives the replacement of either arm, and add per-arm rank logging from the first day.
Do not expect it to help when one arm is consistently uninformative for the corpus. If every query is an identifier lookup, the dense arm adds cost and, as measured here, can subtract quality. If queries are conversational and the corpus has no identifiers, the lexical arm contributes little.
Before production, change three things in this code: replace the flat index and the toy encoder with a real model and an index sized for the corpus, give the dense arm a calibrated way to abstain or route identifier-shaped queries to the lexical arm, and build the labelled query set that turns every choice above from an argument into a measurement. Once that set exists, compare RRF against a tuned convex combination instead of assuming either wins.
References
- The Probabilistic Relevance Framework: BM25 and Beyond — Robertson and Zaragoza, Foundations and Trends in Information Retrieval (2009)
- Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning Methods — Cormack, Clarke and Buettcher, SIGIR 2009
- An Analysis of Fusion Functions for Hybrid Retrieval — Bruch, Gai and Ingber
- Reciprocal rank fusion — Elasticsearch reference
- pgvector README — hybrid search, exact and approximate indexes
- Controlling Text Search: ranking search results — PostgreSQL documentation
Related Articles
AI & Machine Learning14 min read
The Agent Loop Is Forty Lines. The Guards Around It Are the Engineering
A framework-free agent loop in Python, written as a state machine with five explicit exits: validated tool calls, errors returned as observations, step, token and time budgets, and stall detection, all tested with a scripted model and the real SDK.
AI & Machine Learning28 min read
Large Language Model Architecture: How LLMs Actually Work
A technical deep dive into LLM architecture: tokenization, embeddings, transformer blocks, attention mechanisms, and why these systems behave the way they do—including hallucinations and limitations.
Backend Design20 min read
Database Design Patterns for Scale
Scale databases with sharding, replication, and partitioning. Covers PostgreSQL, MySQL, and MongoDB scaling patterns with real performance numbers from production systems.