Sub topic 11
Hybrid search: combining BM25 and vector results
This chapter assumes you can read basic Python and NumPy. It also assumes you know how to embed text and rank documents by cosine similarity, as shown in the earlier chapters on the semantic search pipeline and exact top-k search. You should know what keyword search does. You don't need to know how BM25 is derived.
Why one retriever is not enough
Vector search matches meaning. It finds "Steps to recover access to your account" for the query "How do I reset my password?" even though the two share almost no words. Keyword search matches exact tokens. It is weaker on paraphrase, but it has strengths that embeddings lack:
- Rare identifiers. A query such as
ERR_4012, a product SKU, a function name, or a person's surname is a specific string. An embedding model may mapERR_4012andERR_4021to nearly the same point, or ignore the code entirely. - Out-of-vocabulary terms. Words that were absent or rare in the embedding model's training data get poor vectors. Examples are new product names and internal jargon.
- Predictability. When a keyword result appears, you can see which words matched. A vector hit is harder to explain.
Vector search has the opposite strengths: synonyms, paraphrases, and questions phrased differently from the answer. Hybrid search runs both retrievers and merges the two ranked lists into one. In practice this is often more reliable than either retriever alone, especially on mixed query traffic.
BM25 in one section
BM25 is the standard keyword scoring function. For each query term found in a document, it adds a score built from three ideas:
- Term frequency (TF). A term that appears more often in the document counts more, with diminishing returns. The parameter
k1(commonly 1.2 to 2.0) controls how fast the gain flattens. - Inverse document frequency (IDF). A term found in few documents counts more than a term found in many. "the" contributes almost nothing.
ERR_4012contributes a lot. - Length normalization. A match in a short document counts more than a match in a long one. The parameter
b(0 to 1, commonly 0.75) sets how strong this effect is.
The code below is a small, self-contained BM25 implementation. Production systems use an inverted index (in Elasticsearch, OpenSearch, Lucene, or SQLite FTS5), but the scoring is the same.
import math
import re
from collections import Counter
def tokenize(text):
return re.findall(r"\w+", text.lower())
class BM25:
def __init__(self, docs, k1=1.5, b=0.75):
self.k1, self.b = k1, b
self.tf = [Counter(tokenize(d)) for d in docs]
self.doc_len = [sum(c.values()) for c in self.tf]
self.avgdl = sum(self.doc_len) / len(docs)
df = Counter()
for counts in self.tf:
df.update(counts.keys())
n = len(docs)
self.idf = {t: math.log(1 + (n - f + 0.5) / (f + 0.5)) for t, f in df.items()}
def scores(self, query):
result = []
for tf, dl in zip(self.tf, self.doc_len):
s = 0.0
for term in tokenize(query):
if term not in tf:
continue
f = tf[term]
norm = f + self.k1 * (1 - self.b + self.b * dl / self.avgdl)
s += self.idf[term] * f * (self.k1 + 1) / norm
result.append(s)
return resultA BM25 score is unbounded and depends on the collection. Typical values might be 3 or 17 or 40. A cosine similarity always lies between -1 and 1. That mismatch is the central problem of hybrid search.
Merging two ranked lists
There are two common ways to merge.
Score fusion
Normalize each retriever's scores to a common range, then take a weighted sum: final = w * norm_bm25 + (1 - w) * norm_vector. Min-max normalization is the usual choice. It has pitfalls:
- A single outlier score stretches the range and squashes every other score.
- Normalization is computed per query, so the same raw score can map to different values on different queries.
- If a query returns only one or two keyword hits, min-max scaling can give them a score of 1.0 even when they are weak matches.
- The weight
wneeds tuning on labeled queries, and the best value changes with the corpus.
Reciprocal rank fusion
Reciprocal rank fusion (RRF) ignores scores and uses only rank positions. Each document gets 1 / (k + rank) from every list it appears in, and the contributions are summed. The constant k (60 in the original paper and in most libraries) damps the advantage of the top positions. Because RRF uses no scores, nothing needs normalizing, and a retriever whose scores are on an odd scale cannot dominate.
def reciprocal_rank_fusion(rankings, k=60):
"""rankings: list of ranked lists of document ids, best first."""
scores = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
keyword_ranking = ["d3", "d1", "d7"]
vector_ranking = ["d1", "d5", "d3"]
print(reciprocal_rank_fusion([keyword_ranking, vector_ranking])) # ['d1', 'd3', 'd5', 'd7']Work through the result by hand:
| Document | Keyword rank | Vector rank | RRF score |
|---|---|---|---|
| d1 | 2 | 1 | 1/62 + 1/61 ≈ 0.03252 |
| d3 | 1 | 3 | 1/61 + 1/63 ≈ 0.03226 |
| d5 | none | 2 | 1/62 ≈ 0.01613 |
| d7 | 3 | none | 1/63 ≈ 0.01587 |
Document d1 wins because both retrievers rank it near the top. Documents that only one retriever found still survive, but they rank below documents that both found. This is the main behavior you want from fusion: agreement between retrievers is a strong relevance signal.
The hybrid pipeline
Both retrievers run on the same query. Each returns its own top candidates. Fusion merges them.
A working example
The script below combines the BM25 class with the embedding search from earlier chapters. The corpus includes one document that only a keyword match can find reliably.
import numpy as np
from sentence_transformers import SentenceTransformer
# Uses BM25 and reciprocal_rank_fusion defined above.
docs = [
"Steps to recover access to your account",
"Change your login credentials in the security settings",
"Error ERR_4012 means the payment gateway timed out",
"Our office is open from 9 to 5 on weekdays",
"The cafeteria serves lunch at noon",
]
bm25 = BM25(docs)
model = SentenceTransformer("all-MiniLM-L6-v2")
doc_emb = model.encode(docs, normalize_embeddings=True)
def keyword_ranking(query, depth):
scores = np.array(bm25.scores(query))
order = np.argsort(-scores)
return [int(i) for i in order if scores[i] > 0][:depth]
def vector_ranking(query, depth):
q = model.encode(query, normalize_embeddings=True)
scores = doc_emb @ q
return [int(i) for i in np.argsort(-scores)[:depth]]
def hybrid_search(query, k=3, depth=20):
fused = reciprocal_rank_fusion(
[keyword_ranking(query, depth), vector_ranking(query, depth)]
)
return [docs[i] for i in fused[:k]]
for query in ["What does ERR_4012 mean?", "How do I reset my password?"]:
print(query)
for text in hybrid_search(query):
print(" ", text)Two details matter here. The keyword list drops documents whose BM25 score is zero. If you kept them, the arbitrary order of zero-score documents would add fake rank signal to the fusion. The vector list has no such cutoff, because every document gets some similarity score. Both retrievers return a limited candidate list of depth documents, not the whole corpus.
Design decisions and edge cases
- Candidate depth. Each retriever should return more documents than you finally need. A document ranked 30th in one list and 2nd in the other can still win after fusion. Depths of 50 to 200 per retriever are common. Larger depths cost more latency and make fusion slower, though RRF itself is cheap.
- Identifiers must match. RRF merges by document id. If BM25 indexes chunks and the vector index stores whole documents, ids will not line up. Index both over the same units, normally the same chunks.
- Weighting. Standard RRF treats the lists equally. If your queries are mostly identifier lookups, you can multiply a list's contribution by a weight, such as
weight / (k + rank). Tune weights on labeled queries, not by feel. - The constant
k. A smallkmakes top ranks dominate. A largekflattens the differences. Values from 10 to 100 behave similarly in most cases, so 60 is a safe default and rarely worth tuning first. - Ties. Documents with equal RRF scores come out in an arbitrary order. If you need determinism, break ties by a stable key such as document id.
- Tokenization mismatches. BM25 depends on the analyzer. Stemming, stop-word removal, and handling of punctuation, hyphens, and camelCase change what matches. The
\w+tokenizer above keepsERR_4012whole, but a different analyzer might split it intoerrand4012. - Filters. If a query includes metadata filters such as language or date, apply them inside both retrievers. Filtering after fusion can leave you with fewer than
kresults. - Latency. Two retrievers run in parallel, so total latency is roughly the slower one plus fusion. Many systems use a database that offers both indexes in one query.
When hybrid is worth it
| Situation | Suggested approach |
|---|---|
| Natural-language questions over prose | Vector search alone may be enough. Hybrid adds a small gain. |
| Queries with codes, names, SKUs, or exact phrases | Hybrid. Keyword search protects these queries. |
| Technical documentation and code search | Hybrid. Terms like function names matter. |
| Domain with jargon unknown to the embedding model | Hybrid, or fine-tune the model. |
| Tiny corpus (a few hundred documents) | Either works. Check by measuring, not assuming. |
Exercise
Using reciprocal rank fusion with k = 60, a keyword retriever returns ["a", "b", "c"] and a vector retriever returns ["c", "a", "d"]. Which document ranks first after fusion, and why? Which ranks last?
Show answer
Document "a" ranks first. It gets 1/61 from the keyword list (rank 1) and 1/62 from the vector list (rank 2), a total of about 0.03252. Document "c" gets 1/63 (rank 3) plus 1/61 (rank 1), about 0.03226. Document "b" gets only 1/62 ≈ 0.01613, and "d" gets only 1/63 ≈ 0.01587. So "d" ranks last. The final order is a, c, b, d.
Exercise
Why does the keyword ranking in the example drop documents with a BM25 score of zero, and what could go wrong if they were kept?
Show answer
A zero score means the document shares no query term with the query, so the keyword retriever has no evidence about it. Their order would be arbitrary, such as index order. RRF would still give them rank-based points, so unmatched documents could outrank documents found by only the vector retriever. That adds noise and weakens the benefit of fusion.
Exercise
Your hybrid system returns fewer than k results for queries that use a metadata filter. Name a likely cause and a fix.
Show answer
The filter is probably applied after fusion, so many of the fused candidates are removed. Apply the filter inside both retrievers, before ranking, so each returns candidates that already pass it. You can also raise the candidate depth.