# What Is BM25?

> What BM25 is, how it scores keyword matches, why AI search systems still run it next to embeddings, and where it fails, for your AI interview.

**In short:** BM25 is a keyword ranking function that scores each document by how well its words match the query, giving weight to rare words and adjusting for document length. Some AI search systems run it next to embeddings, because it finds exact codes and names that embeddings can miss.

AI and LLM interview question Q124, Retrieval-augmented generation (RAG). Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-bm25

## Say it in 30 seconds

BM25 is a keyword ranking method. It looks at the words in the question, checks how often each one appears in a document, and gives extra credit to rare words, since a rare word narrows things down. It also scales down long documents, so a long chunk does not win just by being long. Embeddings find similar meaning, but BM25 is better at exact codes and names, so some AI search systems use both.

## Say it in 2 minutes

BM25 stands for Best Matching 25. It is a ranking function: given a question and a set of documents, it scores each document by how well its words match the question. Anthropic calls it an older technique that can assist when embeddings miss exact matches, and it still earns its place because it matches exact words instead of meaning.

The score rests on three ideas. Repeats help, but each extra repeat adds less, so a word used fifty times does not score fifty times higher. Rare words count more than common ones, because a rare word narrows the search. Long documents are scaled down, since a long text has more words that could match by chance. Two tuning settings control how much repeats count and how much length matters.

BM25 earns its place on exact terms. Suppose a bank's support agent is asked about the error code CL-2291-B. An embedding search may return general pages about card errors. BM25 looks for that exact code, so the right handbook page can come first. Anthropic notes that embeddings can miss exact matches that matter, which is why some AI search systems run both searches and merge the two lists.

Its limits are real. BM25 has no sense of meaning, so a question that uses different words from the page may get no credit. The answer is only as good as the words in the query and the chunks. In an interview, say it is a strong first step and a baseline to beat, and that you measure it on real questions before you tune anything.

## What is BM25, in plain words?

BM25 works on the words themselves, so it is a keyword method. You give it a question, and it sorts a set of documents from most to least relevant, based on the words they share with the question.

Picture a claims clerk at an insurer, sorting a pile of case files to find every file that mentions one policy number. The clerk notes which files carry that number, gives more weight to a number that appears in only a few files, and does not let a thick file win just by being thick. BM25 does the same job for an AI assistant searching a company's policy documents.

A chunk is one piece of a document, such as a section or a few paragraphs. Search ranks chunks, not whole files, so each answer can point to a small, exact place.

Some AI assistants search a set of documents before they answer. That pattern is called RAG, short for retrieval-augmented generation. The search step can use embeddings, which are lists of numbers that stand for a text's meaning.

Anthropic's contextual retrieval post calls BM25 a ranking method built on lexical matching, which means matching the actual words.

- **BM25:** A keyword score. Short for Best Matching 25, an old formula that search still uses.
- **Term frequency:** How often a query word appears in one chunk.
- **Inverse document frequency:** How rare a word is across all chunks. Rare words score higher.
- **Document length:** How many words a chunk has. Long chunks are scaled down so they do not win by size.
- **Lexical:** About the exact words typed, not their meaning.

## How does BM25 score a document?

BM25 adds up one score per query word. Each word's score depends on three things: how often it appears in the chunk, how rare it is across all chunks, and how long the chunk is. Repeats have a limit, and long chunks are scaled down, which keeps the score fair.

Repeats help, but not forever. The first mention of a word counts a lot, and the tenth adds much less. Anthropic describes this as a saturation function on term frequency, which stops common words from taking over the ranking.

*Diagram, How BM25 scores one chunk: One chunk's score, built from the question's words. For each word, three signals (repeats with a limit, rarity, and length) combine into a word score. The word scores add up, then chunks are sorted, best first, for the agent to read.*
1. The question's words are looked up in each chunk.
2. Each word's three signals combine, and the word scores add up.
3. Chunks are sorted by score, highest first.

Here is a worked example with made-up numbers. A support bot holds five handbook chunks and gets the question CL-2291-B fraud check. The code uses two tuning settings, set to 1.5 and 0.75, which you adjust on your own questions.

```python
# A made-up bank support search: five handbook chunks, scored with BM25 (k1 = 1.5, b = 0.75).
import math, re
CHUNKS = [
    "Error CL-2291-B means the card issuer blocked the payment. Run a fraud check before any retry.",
    "Card declines at fuel pumps usually clear within 24 hours.",
    "A declined payment may be retried once after a fraud check. A third decline goes to a manager.",
    "Cash withdrawals abroad carry a 2 percent fee on every transaction.",
    "The risk team answers fraud check requests within two working days.",
]
K1, B = 1.5, 0.75
words = lambda text: re.findall(r"[a-z0-9]+", text.lower())
docs = [words(c) for c in CHUNKS]
avg_len = sum(map(len, docs)) / len(docs)
def idf(term):
    df = sum(term in d for d in docs)
    return math.log((len(docs) - df + 0.5) / (df + 0.5) + 1)
def bm25(doc, query):
    total = 0.0
    for term in query:
        tf = doc.count(term)
        total += idf(term) * tf * (K1 + 1) / (tf + K1 * (1 - B + B * len(doc) / avg_len))
    return total
query = words("CL-2291-B fraud check")
scores = [bm25(d, query) for d in docs]
for rank, i in enumerate(sorted(range(len(docs)), key=lambda i: -scores[i]), 1):
    print(f"{rank}. {scores[i]:.2f}  chunk {i + 1}")
```

Output:

```text
1. 4.57  chunk 1
2. 1.18  chunk 5
3. 0.94  chunk 3
4. 0.00  chunk 2
5. 0.00  chunk 4
```

Read the result. Chunk 1 scores far above the rest, because the parts of the code (cl, 2291 and b) appear only there, and rare words carry the most weight. Chunk 5 comes next on the words fraud and check. Chunk 3 holds the same two words once each, but it is longer, so it scores lower. Chunks 2 and 4 score zero, since they share no query word.

> **Tip:** Asked how BM25 works? Name the three signals in order: repeats with a limit, rare words count more, and long chunks scaled down. Then add that it scores words, so it cannot read meaning.

## Why do AI search systems still use it next to embeddings?

An embedding turns text into a list of numbers that captures meaning, so an embedding search finds a page about blocked payments when the question is about declined cards. The catch is that embeddings can blur exact codes, names and part numbers, because the list of numbers stands for the general topic, so an exact code can get lost.

BM25 fills that gap, and it is still a strong yardstick. The DPR paper (2020), which proposed dense passage retrieval, called sparse methods such as TF-IDF or BM25 the de facto method. The BEIR benchmark paper (2021) evaluated 10 state-of-the-art retrieval systems on 18 public datasets and found BM25 a robust baseline.

> "traditional sparse vector space models, such as TF-IDF or BM25, are the de facto method" (DPR paper, 2020 (dense passage retrieval))
>
> "Our results show BM25 is a robust baseline" (BEIR benchmark paper, 2021)
>
> "While embedding models excel at capturing semantic relationships, they can miss crucial exact matches." (Anthropic)

The DPR paper reports that its dense retriever outperformed a strong Lucene-BM25 system, largely by 9% to 19% absolute on top-20 passage retrieval accuracy (how often the right passage appears in the top 20 results). So embeddings can win on some tests, while keyword search still has a role. Teams measure both on their own questions.

*Diagram, Exact words and meaning, merged: The same question sent down two paths. Keyword search finds the exact code, and embeddings find general pages about it. Merging both lists puts the right page first and keeps the general matches behind it.*
1. BM25 looks for the exact code and finds its page.
2. Embedding search finds pages about card errors in general.
3. The exact page moves into the merged list at the top.
4. The general pages join the merged list, lower down.

Anthropic's post describes one such fix, hybrid search: run both searches, then merge the two ranked lists with rank fusion, a way to combine two ranked lists into one.

## Where does BM25 fall short?

BM25 counts words, so it misses meaning. A question about a fee waiver may miss a page that says a charge can be reversed, because no word matches. Typos, synonyms and different word forms need extra work, such as stemming, which trims word endings so that running and run match, or query expansion, which adds related words.

- **Good at: Exact codes and names.** Policy numbers, error codes, product names and rare technical terms. You can see which words matched.
- **Weak at: Meaning and paraphrase.** Synonyms, typos and questions phrased another way. A word missing from the chunk gets no credit.

Tuning helps. The tuning settings, and the tokeniser (the step that splits text into words), change the ranking, so test them on real questions rather than trusting a default.

> **Tip:** Asked what to do when it misses? Check the splitting first: does a code such as CL-2291-B break into the pieces you expect? Then add embeddings or query expansion, rather than tuning BM25 forever.

### How would you use BM25 for 40,000 contracts?

A legal team asks questions over 40,000 supplier contracts. Clause numbers, party names and defined terms must match exactly, so BM25 is a good first layer. The questions people ask can be loose and paraphrased, so embeddings join in.

1. **Split contracts into clauses:** Keep each clause whole, so a hit points to one clause and its number.
2. **Index every clause for keyword search:** BM25 handles clause numbers, party names and defined terms exactly.
3. **Add an embedding index beside it:** Covers loose, paraphrased questions that do not share the contract's words.
4. **Merge, then measure on real questions:** Take a sample of questions from the legal team and check the right clause is in the top results.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: a keyword score that ranks documents by the words they share with the question.
- [ ] The three ideas: repeats with a limit, rare words count more, long documents scaled down.
- [ ] Why it still matters: exact codes, names and rare terms that embeddings can blur.
- [ ] Its limit: no sense of meaning, so synonyms and paraphrases need embeddings or expansion.
- [ ] The practical fix: hybrid search, merged with rank fusion, then measured on real questions.
- [ ] Honest about results: no single method wins everywhere, so test on your own data.

**Common traps**

- Trap: "BM25 is an AI model." Better: It is a formula. It counts words and does not read them for meaning.
- Trap: "Embeddings replaced BM25." Better: Anthropic's post describes running both, because each one misses what the other catches.
- Trap: "More repeats always mean a better match." Better: Repeats count, but each extra one adds less. That is the saturation limit.

## Can you spot the problem?

**Spot the problem:** Your bank's policy page says: card replacement fees and delivery times are listed under Cards. Which customer question will BM25 alone most likely miss?

A. What is the fee for a card replacement?
B. How long do card delivery times take?
C. What does it cost to get a new plastic posted to me?
D. Which cards can I use abroad?

**Answer:** C. It asks about a new plastic and what it costs. The policy page uses the words card replacement fees, so this question shares no words with it, and BM25 finds no match. Add embeddings, or expand the query with related words, such as plastic and replacement.

**Quick check:** Which three ideas make up BM25's score?

A. Model size, temperature and top-p
B. Repeats with a limit, rare words count more, long chunks scaled down
C. Vector length, angle and nearest neighbours
D. Chunk size, overlap and chunk count

**Answer:** B. BM25 scores words: repeats with a limit (term frequency with saturation), rare words counting more (inverse document frequency) and scaling for document length. The other options belong to models, vectors or chunking settings.

## Can you answer these from memory?

**Flash cards**

- **What is BM25?** A keyword ranking function. It scores documents by the words they share with the query.
- **Its biggest strength?** Exact codes, names and rare technical terms that embeddings can blur.
- **Its biggest weakness?** No sense of meaning. Synonyms and paraphrases get no credit.
- **Why do rare words count more?** A rare word narrows the search, so it carries more weight.
- **Why do repeats stop helping?** Each extra repeat adds less. That limit is the saturation.
- **How do you cover BM25's blind spot?** Add embeddings, then merge the two ranked lists into one.

## Likely follow-up questions

- Q123 What is hybrid search (BM25 + vectors)? https://designervenkat.online/interview/ai/what-is-hybrid-search
- Q119 What is approximate nearest-neighbour search? https://designervenkat.online/interview/ai/what-is-approximate-nearest-neighbour-search
- Q125 What is reciprocal rank fusion? (full answer coming)
- Q126 Rerankers: cross-encoder vs bi-encoder? https://designervenkat.online/interview/ai/cross-encoder-vs-bi-encoder-rerankers
- Q131 Retrieval metrics: recall@k, MRR, nDCG? https://designervenkat.online/interview/ai/retrieval-metrics-recall-at-k-mrr-ndcg
- Q127 What are query rewriting and expansion? https://designervenkat.online/interview/ai/what-are-query-rewriting-and-expansion
