---
title: "BM25, Hybrid Search & Reciprocal Rank Fusion (Python Examples)"
description: "How BM25 scores documents, when keyword search beats semantic search, how hybrid search merges both with reciprocal rank fusion (k = 60), and how to add live web results as a third retriever. Dependency-free Python throughout."
category: "guides"
url: https://keirolabs.cloud/blog/bm25-hybrid-search-reciprocal-rank-fusion
published: 2026-11-24
updated: 2026-11-24
---

# BM25, hybrid search and reciprocal rank fusion, explained with code

## The 60-second version

**BM25 is the classic keyword ranking function: it scores a document by how often your query words appear in it, how rare those words are, and how long the document is.** Most search engines have used it or a variant for decades, and it is still the baseline every new retriever gets compared against.

**Hybrid search runs BM25 and a semantic (embedding) search side by side, then merges the two ranked lists.** The usual merge is **reciprocal rank fusion (RRF)**: each document scores `1 / (k + rank)` in every list it appears in, with `k = 60`.

| | BM25 (keyword) | Embeddings (semantic) | Hybrid with RRF |
|---|---|---|---|
| Matches | Exact words | Meaning, paraphrases | Both |
| Great at | Names, error codes, SKUs, rare terms | "How do I…" questions, synonyms | Mixed real-world queries |
| Weak at | Synonyms ("car" vs "automobile") | Exact identifiers, new jargon | Costs two retrievals |
| Needs | A word index | An embedding model and vector index | Both, plus a merge step |

All the code below is plain Python with no dependencies, and it runs as is.

## How does BM25 work?

**BM25 adds up a score for every query word that appears in the document.** Each word's score has three parts:

- **Term frequency, with diminishing returns.** The fifth mention of "rerank" counts less than the first. `k1` (usually 1.2 to 2.0) controls how fast it saturates.
- **Rarity (inverse document frequency).** A match on "reciprocal" is worth far more than a match on "the", because few documents contain it.
- **Length normalization.** A match in a short document counts more than the same match in a long one. `b` (usually 0.75) controls how much.

The formula for one query word `q` in document `D`:

```
score(q, D) = IDF(q) × tf × (k1 + 1) / (tf + k1 × (1 − b + b × |D| / avgdl))
IDF(q)      = ln(1 + (N − n(q) + 0.5) / (n(q) + 0.5))
```

Here `tf` is how often `q` appears in `D`, `|D|` is the document's length in words, `avgdl` is the average length, `N` is the number of documents, and `n(q)` is how many contain `q`.

## BM25 in Python

```python
import math, re
from collections import Counter

def tokenize(text: str) -> list[str]:
    return re.findall(r"[a-z0-9]+", text.lower())

class BM25:
    def __init__(self, docs: list[str], k1: float = 1.5, b: float = 0.75):
        self.k1, self.b = k1, b
        self.docs = [tokenize(d) for d in docs]
        self.tf = [Counter(d) for d in self.docs]
        self.avgdl = sum(len(d) for d in self.docs) / len(self.docs)
        df = Counter(w for d in self.docs for w in set(d))
        n = len(self.docs)
        self.idf = {w: math.log(1 + (n - c + 0.5) / (c + 0.5)) for w, c in df.items()}

    def score(self, query: str, i: int) -> float:
        tf, dl, s = self.tf[i], len(self.docs[i]), 0.0
        for w in tokenize(query):
            if w in tf:
                f = tf[w]
                s += self.idf[w] * f * (self.k1 + 1) / (f + self.k1 * (1 - self.b + self.b * dl / self.avgdl))
        return s

    def search(self, query: str, top_n: int = 10) -> list[tuple[int, float]]:
        scored = [(i, self.score(query, i)) for i in range(len(self.docs))]
        return sorted([x for x in scored if x[1] > 0], key=lambda x: -x[1])[:top_n]

docs = [
    "HTTP 429 Too Many Requests means you hit a rate limit. Retry with backoff.",
    "Rate limits protect an API from overload; plans set requests per minute.",
    "Reciprocal rank fusion merges ranked lists from several retrievers.",
]
print(BM25(docs).search("429 rate limit"))
# [(0, 2.2308...), (1, 0.4640...)]: the doc with the exact error code wins
```

**Why the first document wins:** `429` appears in only one document, so its rarity score is high, and that document also matches `rate` and `limit`. An embedding search might rank the second document just as high, because both are "about rate limits". For error codes, product names and IDs, exact matching is what you want.

For production, use a library or a search engine with BM25 built in (Elasticsearch, OpenSearch, Postgres full-text with a BM25 extension, `rank_bm25` in Python) rather than this class. The scoring is the same.

## Keyword search vs semantic search: when does each win?

| Query | BM25 | Embeddings |
|---|---|---|
| `ERR_CONNECTION_RESET nginx` | ✅ exact tokens | ⚠️ may return generic network errors |
| `pdt_0NnLgFZCGOch0XKaCy4Js` | ✅ | ❌ IDs carry no meaning to an embedding |
| "why does my app get logged out randomly" | ⚠️ needs matching words | ✅ matches "session expiry" pages |
| "cheap car insurance" vs a page saying "affordable auto coverage" | ❌ no shared words | ✅ |
| A brand-new library name | ✅ | ⚠️ the model may never have seen it |

**Neither wins everywhere, which is why hybrid search exists.**

## How does reciprocal rank fusion work?

**RRF merges ranked lists using only the ranks, not the scores.** A document's fused score is the sum, over every list it appears in, of `1 / (k + rank)`:

```
RRF(d) = Σ  1 / (k + rank_i(d))       with k = 60
```

**Why ranks instead of scores?** BM25 scores might run from 0 to 25 while cosine similarities run from 0 to 1. Adding them directly lets one retriever drown out the other, and normalizing them is fragile. Ranks are always comparable. The `k = 60` constant comes from the original RRF paper (Cormack, Clarke and Büttcher, 2009). It flattens the curve so that rank 1 and rank 5 aren't worlds apart, and it works well without tuning.

```python
from collections import defaultdict

def rrf(rankings: list[list[str]], k: int = 60) -> list[tuple[str, float]]:
    scores = defaultdict(float)
    for ranking in rankings:
        for rank, doc_id in enumerate(ranking, start=1):
            scores[doc_id] += 1 / (k + rank)
    return sorted(scores.items(), key=lambda x: -x[1])

bm25_ranking     = ["doc_429", "doc_limits", "doc_retry"]
semantic_ranking = ["doc_limits", "doc_backoff", "doc_429"]
for doc, s in rrf([bm25_ranking, semantic_ranking]):
    print(f"{doc:<12} {s:.5f}")
# doc_limits   0.03252
# doc_429      0.03227
# doc_backoff  0.01613
# doc_retry    0.01587
```

**What happened:** `doc_limits` and `doc_429` both appear in both lists, so they beat documents that only one retriever liked. `doc_limits` edges ahead because its ranks (2 and 1) sum higher than `doc_429`'s (1 and 3).

**Weighting a retriever:** multiply its contribution, `w / (k + rank)`, if you trust it more for your queries. Start with equal weights and only change them if your evaluation set says so.

## How do I build hybrid search over web results?

**Treat live web search as one more retriever and fuse it with your own index.** Your internal docs come from BM25 and embeddings; current facts come from the web. RRF merges all three the same way.

```python
def hybrid_search(query: str, bm25: BM25, doc_ids: list[str], semantic_search, web_search, top_n: int = 10):
    keyword  = [doc_ids[i] for i, _ in bm25.search(query, top_n=50)]
    semantic = semantic_search(query, top_n=50)          # your vector index -> list of ids
    web      = [r["url"] for r in web_search(query)]     # live results -> list of URLs
    return rrf([keyword, semantic, web])[:top_n]
```

**Two practical notes:**

- **Retrieve deep, fuse, then cut.** Pull 50 from each retriever and keep the fused top 10. A document ranked 30th by BM25 and 4th by embeddings is often the right one.
- **Rerank after fusing if quality matters most.** RRF decides what's in the top 50; a cross-encoder decides the final order. See [reranking search results](/blog/reranking-search-results).

**For hybrid search over fresh web pages,** you need the page text, chunked and embedded. Keirolabs `/search/content` (ours) returns the full page text plus chunks with embeddings in one call: set `embeddings.enabled: true` and choose `embeddings.chunkSize` (100 to 2,000). You can then run BM25 over the chunk text and cosine similarity over the vectors without a separate embedding call. Chunk sizing is covered in [chunking strategies for RAG](/blog/chunking-strategies-rag).

## How do I know hybrid search is helping?

**Compare on 50 to 100 real queries with known good results.** Track recall@10 (was a correct document in the top 10?) and MRR (how high was the first correct one?) for BM25 alone, embeddings alone, and hybrid:

```python
def recall_at_k(results: list[str], relevant: set[str], k: int = 10) -> float:
    return len(set(results[:k]) & relevant) / len(relevant)

def mrr(results: list[str], relevant: set[str]) -> float:
    return next((1 / i for i, d in enumerate(results, start=1) if d in relevant), 0.0)

print(recall_at_k(["a", "b", "c"], {"b", "z"}), mrr(["a", "b", "c"], {"b", "z"}))
# 0.5 0.5
```

If hybrid doesn't beat the better single retriever on your queries, keep the simpler one. Usually it does, because real query logs mix exact identifiers with natural-language questions.

## Checklist

- **Use BM25 for exact terms: names, codes, IDs, rare jargon.**
- **Use embeddings for paraphrased, natural-language questions.**
- **Fuse with RRF, k = 60, on ranks, never on raw scores.**
- **Retrieve about 50 per retriever, fuse, keep the top 10.**
- **Add live web search as a third list for anything time-sensitive.**
- **Measure recall@10 and MRR before and after.**

New Keirolabs accounts get up to 2,000 free credits with no card, enough to fuse live web results into your own index and compare ([get a key](https://platform.keirolabs.cloud/register)).
