Özer Cem KELAHMETKELAHMET
AI Simulations · Retrieval (RAG)

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.

Download Markdown

Interactive simulation. It needs JavaScript; the text below explains what it shows.

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: it catches exact names, codes and rare words that dense embeddings miss, and its results are fused with vector search such as HNSW before a reranker 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.

Sources

Last updated Nov 24, 2026
Type to search.
    ↑↓ navigate↵ open