esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

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.

12 min readIntermediateCommon · estimateFacts checked 26 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

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.

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.

Key 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.

How BM25 scores one chunk

Your question

cl, 2291, b, fraud, check

Three signals per word

Repeats, with a limit

more repeats help, less each time

Rare words count more

few chunks contain the word

Long chunks scaled down

fair across short and long text

One score per chunk

each word's score, then added up

Best match first

the ranked list the agent reads

  1. 1The question's words are looked up in each chunk.
  2. 2Each word's three signals combine, and the word scores add up.
  3. 3Chunks are sorted by score, highest first.
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.

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

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.

Exact words and meaning, merged

Keyword search (BM25)

Exact code match

finds the string CL-2291-B

Embedding search

Closest meaning

finds general card error pages

Exact handbook page

the page that explains the code

General card pages

misses the exact code

Merge both lists

keep the best of both

  1. 1BM25 looks for the exact code and finds its page.
  2. 2Embedding search finds pages about card errors in general.
  3. 3The exact page moves into the merged list at the top.
  4. 4The general pages join the merged list, lower down.
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.

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.

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."

    BetterIt is a formula. It counts words and does not read them for meaning.

  • Trap"Embeddings replaced BM25."

    BetterAnthropic's post describes running both, because each one misses what the other catches.

  • Trap"More repeats always mean a better match."

    BetterRepeats 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?

Quick check

Which three ideas make up BM25's score?

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q123What is hybrid search (BM25 + vectors)?11 min
  2. Q119What is approximate nearest-neighbour search?10 min
  3. Q125What is reciprocal rank fusion?Coming soon
  4. Q126Rerankers: cross-encoder vs bi-encoder?12 min
  5. Q131Retrieval metrics: recall@k, MRR, nDCG?12 min
  6. Q127What are query rewriting and expansion?11 min

Last updated on 26 November 2026

Building search over your own documents?

I design and build AI search and agents, including the retrieval layer that decides what the model reads. Book a short call and tell me what your documents look like and what people ask.