Skip to content
Sesha's Blog
Go back

RAG from Scratch, Part 5: BM25

Edit page

RAG from Scratch series: Part 0: Overview · Part 1: Chunking · Part 2: Embeddings, tokens, and metadata · Part 3: The query-time flow · Part 4: Evaluating retrieval · Part 5: BM25 · Next: Part 6: Advanced retrieval

E-4012 is not E-4021

A support engineer searches your knowledge base for “error code E-4012.” Vector search returns the chunk about E-4021.

That isn’t a bug in the embedding model. It’s doing exactly what it was trained to do. Embeddings capture meaning, and to an embedding model, “E-4012” is a few sub-word tokens that together mean roughly “some error code.” E-4012 and E-4021 mean nearly the same thing in that sense, so their vectors land close together. The exact characters, which are the whole point of the query, barely register.

The same thing happens with anything where the exact string matters: product SKUs, version numbers, contract clause numbers, people’s names, and internal jargon.

Keyword search has the opposite strengths:

QueryVector searchBM25
“error code E-4012”Misses: codes look interchangeableFinds it: exact match on a rare token
“how much vacation do I get?” against a chunk about “paid time off”Finds it: understands synonymsMisses: no shared words

Neither one is enough alone, which is why production RAG systems usually run both. That combination, hybrid search, is the subject of Part 6. This post covers the keyword half: BM25, the ranking function behind Elasticsearch, OpenSearch, and Lucene.

The formula

BM25 scores a chunk D against a query Q by adding up one contribution per query term:

score(D, Q) = Σ over query terms t of  IDF(t) × TF(t, D)

Each contribution has two parts.

IDF, or rarity. How unusual is this term across all chunks?

IDF(t) = ln(1 + (N − n + 0.5) / (n + 0.5))

N is the total number of chunks, and n is how many contain the term. A term in almost every chunk gets a weight near 0, while a term in only a few chunks gets a high weight.

TF, or frequency, adjusted for length. How often does the term appear in this chunk?

TF(t, D) = f × (k1 + 1) / (f + k1 × (1 − b + b × len(D) / avg_len))

f is the number of times the term appears in the chunk. Two parameters shape it:

These defaults are what Lucene and Elasticsearch use.

In code, each part is one line:

import math

K1, B = 1.2, 0.75  # Lucene / Elasticsearch defaults

def idf(n_docs, doc_freq):
    """Rare terms get high weight; terms in almost every chunk get ~0."""
    return math.log(1 + (n_docs - doc_freq + 0.5) / (doc_freq + 0.5))

def tf_part(freq, doc_len, avg_len, k1=K1, b=B):
    """Saturating term frequency, normalized for chunk length."""
    return freq * (k1 + 1) / (freq + k1 * (1 - b + b * doc_len / avg_len))

A worked example you can check by hand

Take a corpus of 1,000 chunks with an average length of 100 tokens, and the query “error code E-4012.” First, the IDF of each query term:

TermChunks containing itIDF
error3001.20
code2001.61
e-401225.99

“E-4012” appears in only 2 chunks, so it carries about five times the weight of “error.”

Now three chunks:

ChunkContentsScore
A, about E-4012100 tokens; “error,” “code,” and “e-4012” once each1.20 + 1.61 + 5.99 = 8.80
B, about E-4021100 tokens; “error” ×2, “code” ×21.375 × (1.20 + 1.61) = 3.87
C, general errors200 tokens; “error” ×51.55 × 1.20 = 1.86

Chunk A is at average length with each term once, so each TF part is exactly 1.0 and its score is just the sum of the IDFs. Chunk B mentions the common words twice as often, but saturation means two occurrences are worth 1.375 rather than 2. It scores less than half of A, because it lacks the one rare term. Chunk C repeats “error” five times, but it’s twice the average length, and “error” is the least informative word in the query.

The scratch script reproduces every number:

Worked example:
  IDF(error) = 1.20
  IDF(code) = 1.61
  IDF(e-4012) = 5.99
  A (E-4012)           score = 8.80
  B (E-4021)           score = 3.87
  C (general errors)   score = 1.86

Saturation

Here’s the TF part for a chunk of average length as the term repeats:

Saturation (TF part at average length): {1: 1.0, 2: 1.38, 5: 1.77, 10: 1.96, 100: 2.17}

A term that appears 100 times is worth barely twice as much as a term that appears once. The TF part approaches k1 + 1 = 2.2 and never exceeds it. This stops a chunk from winning by repeating a keyword, which is also what makes BM25 hard to game with keyword stuffing.

Which chunks get scored: the inverted index

You might expect BM25 to score every chunk in the corpus for every query. It doesn’t. At indexing time, the engine builds an inverted index: a map from each term to the chunks that contain it, and how often.

"error"  → 300 chunks
"code"   → 200 chunks
"e-4012" → 2 chunks

At query time, it looks up each query term, takes the union of those lists (at most 502 chunks here, out of 1,000), and scores only those. Chunks without any query term are never touched, and they score 0 anyway.

This is also one reason search engines drop stop words like “the” and “is.” Their lists contain nearly every chunk, which would make the candidate set huge, and their IDF is close to 0, so they add almost nothing to the score. Engines like Elasticsearch go further and skip candidates that provably can’t reach the top k.

BM25 from scratch

The index is a dictionary from term to {chunk_id: frequency}:

import re
from collections import Counter, defaultdict

def tokenize(text):
    # Keeps hyphenated identifiers like "e-4012" as one token.
    return re.findall(r"[a-z0-9]+(?:-[a-z0-9]+)*", text.lower())

class BM25Index:
    def __init__(self, docs):
        self.docs = docs
        self.tokens = [tokenize(d) for d in docs]
        self.avg_len = sum(map(len, self.tokens)) / len(docs)
        self.postings = defaultdict(dict)  # term -> {doc_id: frequency}
        for doc_id, toks in enumerate(self.tokens):
            for term, freq in Counter(toks).items():
                self.postings[term][doc_id] = freq

Search gathers the candidates from the postings lists, then scores only those:

    def search(self, query, top_k=5):
        terms = tokenize(query)
        candidates = set().union(*(self.postings.get(t, {}).keys() for t in terms))
        scores = {}
        for doc_id in candidates:  # only chunks containing >= 1 query term
            scores[doc_id] = sum(
                idf(len(self.docs), len(self.postings[t]))
                * tf_part(self.postings[t][doc_id], len(self.tokens[doc_id]), self.avg_len)
                for t in terms if doc_id in self.postings.get(t, {})
            )
        ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:top_k]
        return [(score, self.docs[doc_id]) for doc_id, score in ranked], len(candidates)

On a five-chunk corpus:

Inverted-index search scored 3 of 5 chunks:
   2.96  Error code E-4012 means the payment token expired.
   1.84  Error code E-4021 is a timeout error; retry the code path.
   0.80  General error handling: log every error and alert on repeated error spikes.

Two chunks, about Project Atlas and sick days, contain none of the query terms. They were never scored and never returned. The ranking matches the worked example: the exact E-4012 chunk first, then E-4021, then the general chunk.

BM25 scores have no fixed scale

Compare the two runs. The E-4012 chunk scored 8.80 in the 1,000-chunk corpus and 2.96 in the five-chunk one. Same query, very different numbers.

That’s because a BM25 score is a sum over query terms, each weighted by an IDF that depends on the corpus. In five chunks, “error” appears in three of them, so its IDF drops to 0.54. A short query of common words might top out around 2, while a long query with rare terms can score over 30.

So a BM25 score only means something compared with other scores for the same query. There’s no fixed scale and no universal threshold, unlike the cosine similarity thresholds from Part 3. This matters as soon as you try to combine BM25 with vector search. Adding a BM25 score of 25 to a cosine similarity of 0.8 lets BM25 dominate completely. That’s why hybrid search fuses ranks instead of scores, using Reciprocal Rank Fusion, which Part 6 covers.

The same thing with rank_bm25

The rank_bm25 library implements the same algorithm:

from rank_bm25 import BM25Okapi

bm25 = BM25Okapi([tokenize(d) for d in docs], k1=1.2, b=0.75)

scores = bm25.get_scores(tokenize("error code E-4012"))
top_2 = bm25.get_top_n(tokenize("error code E-4012"), docs, n=2)

Expect different scores from the scratch version, with the same ranking. BM25 implementations use slightly different IDF formulas. BM25Okapi uses the original formula without the 1 + inside the logarithm, which goes negative for terms that appear in more than half the chunks. In our five-chunk corpus, “error” appears in three, so its IDF would be −0.34. The library replaces negative values with a small positive floor, so common terms still count a little. The 1 + in the Lucene version exists to avoid this problem entirely.

Tokenization decides whether exact match works

BM25’s advantage on identifiers depends entirely on the tokenizer. The scratch code’s regex keeps e-4012 as one token. Many default analyzers split on hyphens instead, turning it into e and 4012. Then a query for E-4012 also matches any chunk containing “4012” anywhere, and the rare-term advantage shrinks.

Before relying on BM25 for codes, SKUs, or version numbers, check how your search engine tokenizes them. Most engines let you test an analyzer on sample text directly.

Run it yourself

From the root of the rag-scratch-to-speciality repo:

uv sync
uv run python code/retrieval/bm25_scratch.py

For the library version:

uv sync --group lib
uv run --group lib python code/retrieval/bm25_lib.py

Full code: bm25_scratch.py · bm25_lib.py

Takeaways

Want to test yourself? The repo’s advanced retrieval quiz covers this part and the next.

Next: Part 6: Advanced retrieval


Edit page
Share this post:

Previous Post
RAG from Scratch, Part 4: Evaluating Retrieval
Next Post
RAG from Scratch, Part 6: Advanced Retrieval