# BM25 ranking step by step: term frequency saturation, IDF and document length normalisation

BM25 still powers the keyword half of most search and RAG systems. Here twenty real Python module docstrings are scored for the query parse file, exactly as Lucene and Elasticsearch score them. Change k1 and b, edit the counts and watch each document's score and the ranking move.

<div data-sim="specx" data-spec="{&#34;head&#34;:&#34;BM25 ranking: term frequency, rarity and document length&#34;,&#34;sub&#34;:&#34;Twenty Python standard-library module docstrings searched for the query \&#34;parse file\&#34;. Move k1 and b and watch the ranking change; edit the counts or paste your own documents.&#34;,&#34;params&#34;:[{&#34;id&#34;:&#34;k1&#34;,&#34;label&#34;:&#34;k1 (term-frequency saturation)&#34;,&#34;min&#34;:0.1,&#34;max&#34;:3,&#34;step&#34;:0.05,&#34;value&#34;:1.2,&#34;note&#34;:&#34;Small = presence is almost all that counts; large = counts keep adding&#34;},{&#34;id&#34;:&#34;b&#34;,&#34;label&#34;:&#34;b (length normalisation)&#34;,&#34;min&#34;:0,&#34;max&#34;:1,&#34;step&#34;:0.05,&#34;value&#34;:0.75,&#34;note&#34;:&#34;0 = ignore length; 1 = full normalisation&#34;}],&#34;data&#34;:{&#34;columns&#34;:[&#34;doc&#34;,&#34;tf_parse&#34;,&#34;tf_file&#34;,&#34;doc_len&#34;],&#34;rows&#34;:[[1,1,0,375],[2,2,1,399],[3,2,2,363],[4,2,7,894],[5,4,0,214],[6,1,0,50],[7,0,2,47],[8,0,1,26],[9,0,0,85],[10,0,0,25],[11,0,17,549],[12,0,0,141],[13,0,1,233],[14,0,0,32],[15,0,0,155],[16,3,8,220],[17,1,16,454],[18,0,0,25],[19,0,0,8],[20,0,0,13]],&#34;note&#34;:&#34;Exact counts of the words parse and file, and the length in words, of 20 CPython 3.13 module docstrings (lowercased, split on non-letters); doc numbers are listed under What you are looking at. Paste your own counts.&#34;},&#34;pre&#34;:[{&#34;id&#34;:&#34;avgdl&#34;,&#34;label&#34;:&#34;Average document length (words)&#34;,&#34;expr&#34;:&#34;mean(doc_len)&#34;,&#34;tex&#34;:&#34;\\text{avgdl} = \\frac{1}{N}\\sum_d |d|&#34;}],&#34;row&#34;:[{&#34;id&#34;:&#34;has_p&#34;,&#34;label&#34;:&#34;has parse&#34;,&#34;expr&#34;:&#34;gt(tf_parse, 0)&#34;,&#34;fmt&#34;:&#34;i&#34;,&#34;hide&#34;:true},{&#34;id&#34;:&#34;has_f&#34;,&#34;label&#34;:&#34;has file&#34;,&#34;expr&#34;:&#34;gt(tf_file, 0)&#34;,&#34;fmt&#34;:&#34;i&#34;,&#34;hide&#34;:true},{&#34;id&#34;:&#34;norm&#34;,&#34;label&#34;:&#34;length factor&#34;,&#34;expr&#34;:&#34;k1*(1 - b + b*doc_len/avgdl)&#34;,&#34;tex&#34;:&#34;K_d = k_1\\Big(1 - b + b\\,\\frac{|d|}{\\text{avgdl}}\\Big)&#34;}],&#34;derived&#34;:[{&#34;id&#34;:&#34;df_p&#34;,&#34;label&#34;:&#34;Documents containing parse&#34;,&#34;expr&#34;:&#34;sum(has_p)&#34;,&#34;fmt&#34;:&#34;i&#34;},{&#34;id&#34;:&#34;df_f&#34;,&#34;label&#34;:&#34;Documents containing file&#34;,&#34;expr&#34;:&#34;sum(has_f)&#34;,&#34;fmt&#34;:&#34;i&#34;},{&#34;id&#34;:&#34;idf_p&#34;,&#34;label&#34;:&#34;IDF of parse&#34;,&#34;expr&#34;:&#34;ln(1 + (n - df_p + 0.5)/(df_p + 0.5))&#34;,&#34;tex&#34;:&#34;\\text{idf}(t) = \\ln\\Big(1 + \\frac{N - n_t + 0.5}{n_t + 0.5}\\Big)&#34;},{&#34;id&#34;:&#34;idf_f&#34;,&#34;label&#34;:&#34;IDF of file&#34;,&#34;expr&#34;:&#34;ln(1 + (n - df_f + 0.5)/(df_f + 0.5))&#34;}],&#34;row2&#34;:[{&#34;id&#34;:&#34;w_p&#34;,&#34;label&#34;:&#34;tf weight parse&#34;,&#34;expr&#34;:&#34;tf_parse/(tf_parse + norm)&#34;,&#34;tex&#34;:&#34;\\text{tf}_{t,d} = \\frac{f_{t,d}}{f_{t,d} + K_d}&#34;},{&#34;id&#34;:&#34;w_f&#34;,&#34;label&#34;:&#34;tf weight file&#34;,&#34;expr&#34;:&#34;tf_file/(tf_file + norm)&#34;},{&#34;id&#34;:&#34;score&#34;,&#34;label&#34;:&#34;BM25 score&#34;,&#34;expr&#34;:&#34;idf_p*w_p + idf_f*w_f&#34;,&#34;tex&#34;:&#34;\\text{score}(q,d) = \\sum_{t \\in q} \\text{idf}(t)\\,\\text{tf}_{t,d}&#34;},{&#34;id&#34;:&#34;matched&#34;,&#34;label&#34;:&#34;matches&#34;,&#34;expr&#34;:&#34;gt(score, 0)&#34;,&#34;fmt&#34;:&#34;i&#34;,&#34;hide&#34;:true}],&#34;post&#34;:[{&#34;id&#34;:&#34;top&#34;,&#34;label&#34;:&#34;Best score&#34;,&#34;expr&#34;:&#34;amax(score)&#34;},{&#34;id&#34;:&#34;n_match&#34;,&#34;label&#34;:&#34;Documents matching a term&#34;,&#34;expr&#34;:&#34;sum(matched)&#34;,&#34;fmt&#34;:&#34;i&#34;},{&#34;id&#34;:&#34;max_score&#34;,&#34;label&#34;:&#34;Ceiling: both idf values added&#34;,&#34;expr&#34;:&#34;idf_p + idf_f&#34;,&#34;note&#34;:&#34;the score a document approaches as both counts grow&#34;}],&#34;chart&#34;:{&#34;title&#34;:&#34;How the tf weight saturates with term count&#34;,&#34;x&#34;:{&#34;var&#34;:&#34;t&#34;,&#34;label&#34;:&#34;Times the term appears in the document&#34;,&#34;from&#34;:0,&#34;to&#34;:20},&#34;y&#34;:{&#34;from&#34;:0,&#34;to&#34;:1},&#34;series&#34;:[{&#34;label&#34;:&#34;Average-length document&#34;,&#34;expr&#34;:&#34;t/(t + k1)&#34;},{&#34;label&#34;:&#34;Document a quarter of average length&#34;,&#34;expr&#34;:&#34;t/(t + k1*(1 - b + b*0.25))&#34;},{&#34;label&#34;:&#34;Document 2.5 times average length&#34;,&#34;expr&#34;:&#34;t/(t + k1*(1 - b + b*2.5))&#34;,&#34;dash&#34;:true}],&#34;fit&#34;:{&#34;x&#34;:&#34;tf_file&#34;,&#34;y&#34;:&#34;w_f&#34;,&#34;label&#34;:&#34;tf weight of file in each document&#34;},&#34;mark&#34;:&#34;k1&#34;},&#34;level&#34;:&#34;intermediate&#34;,&#34;bars&#34;:{&#34;title&#34;:&#34;BM25 score of each document for \&#34;parse file\&#34;&#34;,&#34;y&#34;:&#34;score&#34;,&#34;label&#34;:&#34;doc&#34;},&#34;steps&#34;:[{&#34;title&#34;:&#34;Measure the collection&#34;,&#34;text&#34;:&#34;N = 20 documents with an average length of {avgdl} words. parse appears in {df_p} documents and file in {df_f}.&#34;,&#34;show&#34;:[&#34;avgdl&#34;,&#34;df_p&#34;,&#34;df_f&#34;]},{&#34;title&#34;:&#34;Weigh each term by rarity&#34;,&#34;text&#34;:&#34;Rarer terms carry more evidence: idf(parse) = {idf_p} and idf(file) = {idf_f}.&#34;,&#34;show&#34;:[&#34;idf_p&#34;,&#34;idf_f&#34;]},{&#34;title&#34;:&#34;Normalise for length&#34;,&#34;text&#34;:&#34;Each document gets K = k1 × (1 − b + b × length / avgdl), with k1 = {k1} and b = {b}. Long documents get a larger K, so each occurrence counts for less.&#34;},{&#34;title&#34;:&#34;Saturate the term counts&#34;,&#34;text&#34;:&#34;The tf weight f / (f + K) rises quickly and levels off below 1: the tenth mention adds far less than the first.&#34;},{&#34;title&#34;:&#34;Add up the score&#34;,&#34;text&#34;:&#34;Score = idf × tf weight, summed over the query terms. {n_match} documents match at least one term; the best scores {top}, against a ceiling of {max_score}.&#34;,&#34;show&#34;:[&#34;top&#34;,&#34;n_match&#34;,&#34;max_score&#34;]}]}"><p>Interactive simulation. It needs JavaScript; the text below explains what it shows.</p></div>

## What you are looking at

Each row of the data grid is one document: the docstring of a Python standard-library module in CPython 3.13, such as `plistlib`, `wave`, `argparse` or `fileinput`. For each docstring the grid holds how often the exact words parse and file appear, and its length in words. The query is "parse file", so these three numbers are all BM25 needs. The document numbers are: 1 `json`, 2 `csv`, 3 `argparse`, 4 `configparser`, 5 `urllib.parse`, 6 `xml.dom.minidom`, 7 `pickle`, 8 `gzip`, 9 `os.path`, 10 `shutil`, 11 `fileinput`, 12 `tempfile`, 13 `io`, 14 `logging`, 15 `sqlite3`, 16 `plistlib`, 17 `wave`, 18 `pathlib`, 19 `tarfile`, 20 `zipfile`.

The two sliders are BM25's parameters. k1 controls how fast repeated mentions stop adding to the score. b controls how strongly long documents are penalised. The bars show the BM25 score of each document, so you can read the ranking at a glance. The chart shows the tf weight of a term against how often it appears, for a document of average length, one a quarter as long and one 2.5 times as long; the dots are the tf weight of file in each real document. The vertical line marks k1, the count at which an average-length document reaches half of the maximum weight.

A useful picture: a judge reading essays. The first time an essay mentions the topic is strong evidence; the tenth mention adds little. A rare word is better evidence than a common one. A short essay that mentions the topic twice is more focused than a long one that mentions it twice.

## The algorithm

1. **Measure the collection.** Count the documents N and the average length avgdl. For each query term t, count n_t, the number of documents that contain it.
2. **Weigh terms by rarity.** idf(t) = ln(1 + (N − n_t + 0.5) / (n_t + 0.5)). This is the form Lucene uses; the 1 + inside the logarithm keeps it positive even for terms in most documents.
3. **Normalise for length.** Each document gets K = k1 × (1 − b + b × |d| / avgdl). With b = 0 length is ignored; with b = 1 the penalty is fully proportional to length.
4. **Saturate term counts.** The tf weight is f / (f + K): 0 for no mentions, rising quickly, and never reaching 1.
5. **Add up.** The score is the sum of idf × tf weight over the query terms. Sort the documents by score.

The textbook form multiplies the tf weight by (k1 + 1). Lucene dropped that constant because it scales every score equally and does not change the ranking, so the numbers here match what Elasticsearch's explain output shows.

**Worked example (k1 = 1.2, b = 0.75).** The twenty docstrings average 215.4 words. parse appears in 8 of them and file in 9, so idf(parse) = ln(1 + 12.5 / 8.5) = 0.904 and idf(file) = ln(1 + 11.5 / 9.5) = 0.793. `plistlib` has 220 words, 3 × parse and 8 × file. Its K = 1.2 × (0.25 + 0.75 × 220 / 215.4) = 1.219. The tf weights are 3 / 4.219 = 0.711 and 8 / 9.219 = 0.868, so its score is 0.904 × 0.711 + 0.793 × 0.868 = 1.331, the top of the ranking. `fileinput` mentions file 17 times, but at 549 words its K is 2.594, its tf weight is 0.868 (the same as `plistlib`'s 8 mentions) and with no parse it scores only 0.688. Twelve documents match at least one term; the ceiling any document can approach is 0.904 + 0.793 = 1.698.

## Things to try

- Set b to 0, so length no longer matters. `configparser`, the longest docstring with 894 words, climbs from fourth place (0.803) to second (1.242), because its 7 mentions of file are no longer diluted.
- Set b to 1 for full normalisation. `plistlib` stays first at 1.330 and `wave` second, while `configparser` falls to 0.723.
- Raise k1 to 3. Counts matter more: `fileinput` with 17 mentions of file moves up to third place with 0.574.
- Lower k1 to 0.1. Almost any mention gives nearly the full weight, so documents that contain both words bunch together between 1.52 and 1.66, and `urllib.parse`, with only parse, drops to 0.883.
- Edit `gzip` (document 8, only 26 words) and change its file count from 1 to 3. Its score rises from 0.563 to 0.698 and it jumps from tenth to sixth place, past `fileinput` with 17 mentions: short documents reach high tf weights with few mentions.

## How it works in real systems

Lucene's BM25Similarity defaults to k1 = 1.2 and b = 0.75, and Elasticsearch, which builds on Lucene, uses the same defaults. The statistics are kept per field and, in Elasticsearch, per shard: docCount is the number of documents in the shard that have the field, which is why the same document can score slightly differently in two indexes of different sizes.

In retrieval-augmented generation BM25 is the keyword half of [hybrid search](/ai-simulations/rag-hybrid): it catches exact names, codes and rare words that dense embeddings miss, and its results are fused with vector search such as [HNSW](/ai-simulations/hnsw-vector-search) before a [reranker](/ai-simulations/rag-rerank) orders the final list. Tuning k1 and b per field (titles want little length normalisation, long bodies more) is often a cheap win. See also the [BM25 tool page](/tools/bm25).

## Sources

- [Lucene BM25Similarity source (idf and tf formulas, defaults)](https://github.com/apache/lucene/blob/main/lucene/core/src/java/org/apache/lucene/search/similarities/BM25Similarity.java)
- [Lucene 9.9 BM25Similarity API documentation](https://lucene.apache.org/core/9_9_0/core/org/apache/lucene/search/similarities/BM25Similarity.html)
- [Elastic: Practical BM25, part 2 (k1, b and Elasticsearch defaults)](https://www.elastic.co/blog/practical-bm25-part-2-the-bm25-algorithm-and-its-variables)
- [Okapi BM25 (Wikipedia)](https://en.wikipedia.org/wiki/Okapi_BM25)
