BM25

Also known as: Best Matching 25 · Okapi BM25

On this page 7

BM25, short for Best Matching 25 and also known as Okapi BM25, is a probabilistic ranking function that scores how relevant a document is to a keyword query by combining how often query terms appear in the document, how rare those terms are across the collection and how long the document is. In artificial intelligence systems for retrieval and knowledge access, it is the standard lexical retrieval baseline and a core component of hybrid search and RAG pipelines.

BM25 grew out of the probabilistic relevance framework developed by Stephen Robertson, Karen Spärck Jones and colleagues, and was refined in the Okapi system at City University London during the 1990s. It is the default similarity in Lucene, Elasticsearch and OpenSearch, and it remains hard to beat on exact-term queries despite the rise of embeddings.

How BM25 scores a document

BM25 computes a score for each document by summing a contribution for every query term that the document contains. Each contribution multiplies an inverse document frequency weight by a saturated, length-normalized term frequency, so rare terms count more and repeated terms help with diminishing returns.

In compact form, the contribution of term q is IDF(q) × f × (k1 + 1) / (f + k1 × (1 − b + b × dl / avgdl)), where f is the term count in the document, dl the document length and avgdl the average length in the collection. The table below explains each element.

ComponentMeaningEffect on the score
Term frequency fOccurrences of the term in the documentRaises the score, but saturates
Inverse document frequencyLogarithm of how rare the term isRare terms dominate common ones
Document length dlNumber of tokens in the documentLong documents are penalized
Average length avgdlMean document length in the indexReference point for normalization
k1Saturation parameterControls how fast repeated terms stop helping
bLength normalization parameterControls how strongly length is penalized
Components of the BM25 formula

Term frequency saturation is the feature that distinguishes BM25 from classic TF-IDF. In TF-IDF, a term repeated fifty times can overwhelm the score; in BM25, the contribution approaches an upper bound of IDF × (k1 + 1), so keyword stuffing yields little benefit.

Tuning the k1 and b parameters

BM25 has only two free parameters, which makes it robust and easy to deploy. The common defaults of k1 = 1.2 and b = 0.75 work well across many collections, but tuning on a labeled query set can bring measurable gains for specialized content.

Parameter settingBehaviorWhen it fits
k1 near 0Term frequency ignored, presence onlyShort texts such as titles or product names
k1 of 1.2 to 2.0Moderate saturationGeneral web pages and documents
b = 0No length normalizationCollections of uniform length
b = 0.75Standard normalizationMixed document lengths
b near 1Full normalization to average lengthLong documents that repeat terms by size alone
Effect of BM25 parameter values

Parameters should be tuned with a retrieval metric such as nDCG or recall at k on representative queries. Changing them without evaluation often helps one query type and harms another.

BM25 compared with other retrieval methods

BM25 represents documents as sparse bags of words, while dense retrieval represents them as embeddings compared by vector similarity. The two approaches fail on different queries, which is why they are frequently combined.

ApproachMatching basisStrengthWeakness
TF-IDFWeighted exact termsSimple and fastNo saturation or proper length handling
BM25Saturated, normalized exact termsNames, codes and rare termsMisses synonyms and paraphrases
Semantic search with embeddingsMeaning in vector spaceParaphrases and natural questionsWeak on exact identifiers
Learned sparse retrievalModel-weighted and expanded termsAdds vocabulary expansionRequires model training and inference
Hybrid searchBM25 plus dense scoresCovers both failure modesMore components to tune
BM25 and neighboring retrieval approaches

In hybrid search, the BM25 and dense result lists are merged, often with reciprocal rank fusion, and the combined candidates are passed to a reranking model. BM25 is particularly valuable for part numbers, error codes, legal citations and personal names, which embeddings tend to blur.

BM25 in RAG pipelines

In retrieval-augmented generation, BM25 serves as a fast first-stage retriever over chunked documents. It requires no GPU, indexes quickly with an inverted index and gives transparent, explainable scores, which simplifies debugging when a language model answers from the wrong passage.

Chunking affects BM25 directly, because chunk length feeds the length normalization. Very short chunks inflate scores for incidental matches, while very long chunks dilute relevant passages. Query rewriting can also help, since adding likely keywords compensates for the vocabulary mismatch that BM25 cannot resolve on its own.

Limitations and common mistakes

  • Vocabulary mismatch: a query for car does not match automobile without synonyms or expansion.
  • Poor text analysis: missing stemming, wrong language analyzers or bad tokenization of codes reduce recall.
  • Comparing raw scores across queries: BM25 scores are not calibrated probabilities.
  • Ignoring field structure: titles and body text usually need separate weights, as in BM25F.
  • Skipping stopword review: removing words such as not can change meaning in some domains.

Most BM25 problems are solved in the analysis chain rather than the formula, so tokenizers, stemmers and synonym lists deserve as much attention as k1 and b.

Stripped to the essentials

BM25 is a recipe for ranking search results by keywords. It gives a document more points when it contains the words you searched for, extra points when those words are rare and specific, and fewer points when the document is very long.

Repeating a word many times helps only a little, so documents cannot cheat by stuffing keywords. The method is old, simple and fast, yet still very good at finding exact names and codes.

Where it is applied

An industrial equipment supplier builds a support assistant that answers technician questions from about 40,000 pages of manuals. A pure embedding search often fails on queries such as error E-4127 on pump model PX-220, returning pages about similar pumps but the wrong error.

The team adds BM25 over the same chunks with an analyzer that keeps codes intact, fuses both result lists with reciprocal rank fusion and reranks the top 50 candidates. Exact error codes now reach the top results reliably, while natural-language questions still benefit from embeddings. The answer quality on the team’s test set of real support tickets improves clearly for code-based queries without slowing responses noticeably.