Lesson 23.2 · 2 of 7 · 4 min read · Reviewed 24 Nov 2026
Hybrid search: BM25 plus embeddings
By the end, you can
- Combine keyword and vector search.
- Merge rankings with reciprocal rank fusion.
Why both
| Query | Keyword search | Vector search |
|---|---|---|
| “E-4012 on startup” | Finds the exact code | May find similar-sounding errors |
| “laptop won’t turn on” | Misses “device fails to power up” | Finds it |
| “Dr. Okafor’s referral” | Finds the name | May return other referrals |
BM25 in one paragraph
BM25BM25: A classic keyword ranking function that scores documents by term frequency and rarity. scores a document higher when it contains the query’s words, especially rare ones, adjusted for document length. It needs no model, is fast, and is very good at exact terms.
Merging with reciprocal rank fusion (RRF)
Scores from the two methods aren’t on the same scale, so merge by rank:
RRF score(doc) = sum over lists of 1 / (k + rank in that list) (k often 60)
doc keyword rank vector rank RRF
A 1 8 1/61 + 1/68
B 5 1 1/65 + 1/61
C - 2 1/62
Documents high in either list rise to the top; documents high in both rise most.
Then rerank
Hybrid search makes a better shortlist. A reranker (23.3) then orders it by true relevance. Anthropic’s contextual retrievalContextual retrieval: Adding a short, document-aware context sentence to each chunk before embedding and indexing it. write-up reports that combining contextual embeddingsEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together., BM25 and rerankingReranking: Re-scoring an initial set of retrieved results with a more accurate model to put the best ones first. cut retrieval failures substantially compared with embeddings alone (23.5).
Key points
- Keyword search (BM25) finds exact terms: codes, names, rare words; vectors find meaning.
- Hybrid search runs both and merges the results, catching what either alone would miss.
- Reciprocal rank fusion is a simple, robust way to merge ranked lists without tuning score scales.
Implement BM25 and hybrid search
Score documents with BM25, merge them with a vector ranking using reciprocal rank fusion, and compare the three top lists.
You will have: A bm25() function, an rrf() merge and the top 3 results for keyword, vector and hybrid search.
Steps
- Read the six documents and the given vector ranking for the query 'E-4012 on startup'.
- Implement BM25 with k1 = 1.5 and b = 0.75 over the tokenised documents.
- Rank documents by BM25 score and merge with the vector ranking using RRF (k = 60).
- Print the top 3 for each method.
Done when
- Keyword search ranks the E-4012 fix guide first.
- Vector search misses the exact code at the top.
- Hybrid search has the fix guide in its top 2 and still finds 'Device fails to power up', which keyword search misses.
Open in the Playground No API key needed.
Starter code (Python)
import math, re
DOCS = {
"fix-guide": "Error e-4012 fix guide: the device failed its power check on startup",
"startup": "Startup errors overview and what each error light means",
"power-up": "Device fails to power up after charging overnight",
"notes": "Release notes 4.0.12 with fixes for startup timing",
"e4011": "Error e-4011 battery warning on startup",
"charging": "Charging tips to keep the battery healthy",
}
VECTOR_RANK = ["startup", "power-up", "e4011", "fix-guide", "charging", "notes"] # from an embedding model
QUERY = "E-4012 on startup"
def tokens(text):
return re.findall(r"[a-z0-9-]+", text.lower())
def bm25(query, docs, k1=1.5, b=0.75):
# TODO: idf = log((N - df + 0.5) / (df + 0.5) + 1); tf part = tf*(k1+1) / (tf + k1*(1 - b + b*len/avglen))
return {d: 0.0 for d in docs}
def rrf(lists, k=60):
# TODO: sum 1 / (k + rank) over lists, rank starting at 1
return lists[0]
scores = bm25(QUERY, DOCS)
kw = sorted(DOCS, key=lambda d: -scores[d])
print("keyword:", kw[:3])
print("vector: ", VECTOR_RANK[:3])
print("hybrid: ", rrf([kw, VECTOR_RANK])[:3])
Show a solution
import math, re
DOCS = {
"fix-guide": "Error e-4012 fix guide: the device failed its power check on startup",
"startup": "Startup errors overview and what each error light means",
"power-up": "Device fails to power up after charging overnight",
"notes": "Release notes 4.0.12 with fixes for startup timing",
"e4011": "Error e-4011 battery warning on startup",
"charging": "Charging tips to keep the battery healthy",
}
VECTOR_RANK = ["startup", "power-up", "e4011", "fix-guide", "charging", "notes"] # from an embedding model
QUERY = "E-4012 on startup"
def tokens(text):
return re.findall(r"[a-z0-9-]+", text.lower())
def bm25(query, docs, k1=1.5, b=0.75):
toks = {d: tokens(t) for d, t in docs.items()}
n = len(docs); avg = sum(len(t) for t in toks.values()) / n
scores = {d: 0.0 for d in docs}
for term in set(tokens(query)):
df = sum(term in t for t in toks.values())
if not df:
continue
idf = math.log((n - df + 0.5) / (df + 0.5) + 1)
for d, t in toks.items():
tf = t.count(term)
scores[d] += idf * tf * (k1 + 1) / (tf + k1 * (1 - b + b * len(t) / avg))
return scores
def rrf(lists, k=60):
s = {}
for ranked in lists:
for rank, doc in enumerate(ranked, start=1):
s[doc] = s.get(doc, 0) + 1 / (k + rank)
return sorted(s, key=lambda d: (-s[d], d))
scores = bm25(QUERY, DOCS)
kw = [d for d in sorted(DOCS, key=lambda d: (-scores[d], d)) if scores[d] > 0]
print("keyword:", kw[:3])
print("vector: ", VECTOR_RANK[:3])
hybrid = rrf([kw, VECTOR_RANK])
print("hybrid: ", hybrid[:3])
print("fix guide in hybrid top 2:", "fix-guide" in hybrid[:2])
print("power-up found by keyword:", "power-up" in kw, "| by hybrid:", "power-up" in hybrid)