BM25 (Best Matching 25) is a ranking function used by search engines to score how relevant a document is to a query, and its two most important inputs are term frequency (how often a query word appears in a document) and document length (how long the document is). Term frequency increases a score but with diminishing returns, while longer documents are penalized because they have more chances to contain a term by chance. This article explains the exact formulas, the intuition behind them, and how to choose BM25 parameters for your own search system.
Background: From TF-IDF to BM25
Before BM25, search engines commonly used TF-IDF (term frequency–inverse document frequency). TF-IDF scores a document by multiplying:
- Term frequency (TF): how many times the query term appears in the document.
- Inverse document frequency (IDF): a measure of how rare the term is across all documents (rarer terms get higher weight).
TF-IDF has a known flaw: if you double the term frequency, the score doubles, which means a document that mentions a word 10 times gets twice the score of one that mentions it 5 times, even though the 10th mention adds little new information. BM25, introduced by Stephen Robertson and Karen Spärck Jones in the 1990s, fixes this by applying a saturation curve to term frequency and by normalizing for document length. It became the default ranking function in many open-source search engines like Elasticsearch and Lucene, and it still underpins modern search despite the rise of neural ranking models.
How BM25 Term Frequency Works
In BM25, the term frequency component is not linear. The formula for the term frequency part of the score for a single term t in document d is:
TF_component = (f(qi, D) * (k1 + 1)) / (f(qi, D) + k1 * (1 - b + b * (|D| / avgdl)))
Where:
- f(qi, D) is the raw term frequency (count of term qi in document D).
- k1 is a saturation parameter (default 1.2). It controls how quickly the term frequency saturates. A higher k1 means the score keeps increasing more with additional mentions; a lower k1 means it saturates faster.
- b is a length normalization parameter (default 0.75). It controls how much the document length affects the score.
- |D| is the document length (in words or tokens).
- avgdl is the average document length across the entire corpus.
The effect of k1: if you plot the TF component against f(qi, D), you get a curve that rises quickly for the first few occurrences and then flattens. For example, with k1=1.2, a term appearing 5 times scores about 2.4 times higher than a term appearing once, but a term appearing 20 times scores only about 3.3 times higher than once. This is the “diminishing returns” that makes BM25 more robust than raw TF.
How Document Length Normalization Works
Longer documents naturally have higher term frequencies simply because they have more words. Without normalization, a 10,000-word article would almost always outrank a 500-word snippet for any query. BM25 handles this with the denominator term k1 * (1 - b + b * (|D| / avgdl)).
When |D| equals avgdl (the document is exactly average length), the factor becomes 1 - b + b = 1, so no adjustment. When |D| is larger than avgdl, the denominator increases, reducing the score. When |D| is smaller, the denominator decreases, boosting the score. The parameter b controls how strong this effect is: b=0 means no length normalization (length has no effect), b=1 means full normalization (length matters as much as possible). The default b=0.75 is a compromise that works well for most corpora.
This is why a short document that mentions a term once can outrank a long document that mentions it three times—the short document’s term density is higher, and BM25 interprets that as stronger relevance.
The Full BM25 Score Formula
Putting it all together, the BM25 score for a query Q containing terms q1, q2, ..., qn is:
score(D, Q) = Σ (IDF(qi) * TF_component(qi, D))
Where the IDF (inverse document frequency) is typically computed as:
IDF(qi) = ln((N - n(qi) + 0.5) / (n(qi) + 0.5) + 1)
Where:
- N is the total number of documents in the corpus.
- n(qi) is the number of documents containing term qi.
The +1 inside the logarithm prevents negative IDF values for terms that appear in more than half of the documents. Terms that appear in many documents get a low IDF, so common words like “the” contribute very little to the score. Terms that appear in few documents get a high IDF, so rare terms dominate the score.
The final score is the sum of these components across all query terms. Note that BM25 does not consider term proximity or phrase order—it treats each query term independently. For phrase queries, search engines often use a separate scoring mechanism.
Choosing k1 and b Parameters
The defaults k1=1.2 and b=0.75 are a good starting point, but they are not universal. Here’s how to think about tuning them:
- k1 higher (e.g., 2.0): Gives more weight to repeated terms. Useful when documents are long and repetition is meaningful (e.g., academic papers).
- k1 lower (e.g., 0.5): Saturates faster, so the first mention matters most. Useful for short documents like tweets or product titles.
- b higher (e.g., 1.0): Penalizes long documents more heavily. Useful when document length varies wildly and you want to favor concise answers.
- b lower (e.g., 0.3): Reduces length penalty. Useful when all documents are roughly the same length, so length normalization is less needed.
If you use Elasticsearch, you can set these per-field in the similarity settings. If you’re implementing BM25 yourself, you can experiment with a small validation set to see which values improve precision or recall.
Common Problems and Misconceptions
Misconception: BM25 is obsolete because of neural search. While vector search (e.g., embeddings) is powerful for semantic matching, BM25 is still widely used for exact keyword matching, especially in e-commerce, legal, and code search where precision matters. Many production systems use a hybrid approach.
Problem: Stop words and punctuation. BM25 scores common words very low due to IDF, but they still add noise. Most search engines remove stop words before indexing, but if you don’t, you may see odd rankings.
Problem: Very long documents. For extremely long documents (e.g., entire books), even with length normalization, the raw term count can be huge. Some systems truncate documents or use a separate field for the title and body.
Problem: Sparse term distribution. If your corpus has many documents that contain a term only once, the IDF can be very high, causing a single rare term to dominate the score. This is usually fine, but if you see inconsistent results, consider using a smoothed IDF variant.
Comparison: BM25 vs. TF-IDF vs. DFR
TF-IDF is simpler but linear in term frequency. BM25 adds saturation and length normalization, making it more robust. Divergence from Randomness (DFR) is another probabilistic model that sometimes outperforms BM25 on specific datasets, but BM25 is more widely implemented and easier to tune. In practice, BM25 is the baseline that any new ranking function must beat.
Frequently Asked Questions
Q: Why does BM25 use a logarithm for IDF?
A: The logarithm compresses the range of IDF values. Without it, a term appearing in 1 document out of 1,000 would have an IDF of 999, while a term appearing in 500 documents would have an IDF of 1, leading to extreme scores. The log makes the difference more moderate, so rare terms are boosted but not overwhelmingly.
Q: What is the ideal value for k1?
A: There is no universal ideal. The default 1.2 works for most text corpora, but if your documents are very short (e.g., product titles), you might lower it to 0.5–1.0. If they are very long (e.g., research papers), you might raise it to 1.5–2.0. Test with your own data.
Q: Does BM25 consider word order?
A: No, BM25 is a bag-of-words model. It treats each query term independently. For phrase queries, search engines like Elasticsearch use a separate scorer that combines BM25 with position information, but the base BM25 formula itself does not use order.
Q: How does BM25 handle synonyms?
A: It doesn’t. BM25 only matches exact terms. If you need synonym handling, you must expand the query or index with synonyms (e.g., using a synonym filter in Elasticsearch). This is a common reason why people combine BM25 with vector search.
Q: Can BM25 produce negative scores?
A: Yes, if a term appears in more than half of the documents, the IDF can become negative (because of the +1 inside the log, it rarely goes negative, but it can approach zero). Most implementations clamp negative IDF to 0 to avoid negative scores, but not all do. Check your library’s behavior.
Q: Is BM25 used in Google?
A: Google’s exact ranking algorithm is not public, but it is known to use many signals beyond BM25, including neural models. BM25 is more commonly found in open-source search engines like Elasticsearch, Solr, and OpenSearch, as well as in many custom search systems.