Sub topic 4
Ranking results with TF-IDF and BM25
This chapter assumes you know how an inverted index maps terms to documents and how text analysis turns raw text into terms. Both are covered in the previous chapters. Here we look at what happens after the index finds the matching documents: putting them in a useful order.
Why matching is not enough
A query like running shoes can match thousands of products. Users read the first few results, so the order matters as much as the match. A search service therefore gives every matching document a numeric score and returns the highest scores first.
A good score should reflect three observations:
- A document that mentions a query term more often is probably more relevant.
- A rare term tells you more than a common one. Matching
gortexsays more than matchingthe. - A long document mentions more terms by chance, so a match in a short document is stronger evidence.
TF-IDF captures the first two. BM25 refines all three, and it is the default in Elasticsearch, OpenSearch, and Lucene-based engines.
TF-IDF
TF-IDF multiplies two quantities for each query term in each document:
- Term frequency (tf) is how many times the term appears in the document.
- Inverse document frequency (idf) measures how rare the term is across the whole index. With
Ndocuments anddfof them containing the term, a common form islog(N / df).
The document's score is the sum of tf × idf over the query terms.
import math
def tf_idf(tf, df, n_docs):
return tf * math.log(n_docs / df)
# 1000 documents. "the" appears in 990 of them, "gortex" in 5.
print(round(tf_idf(tf=5, df=990, n_docs=1000), 3)) # 0.05
print(round(tf_idf(tf=2, df=5, n_docs=1000), 3)) # 10.597A document that says "the" five times scores far below one that says "gortex" twice. That is the intended behavior.
TF-IDF has two weaknesses:
- Raw tf grows without limit. A page that repeats a keyword 50 times beats a page that uses it naturally 5 times, which invites keyword stuffing.
- It ignores document length. Long documents contain more terms, so they collect more tf on average.
BM25
BM25 keeps the idf idea and fixes both weaknesses with two tuning parameters. The score for one term in one document is:
import math
def bm25_term_score(tf, df, n_docs, doc_len, avg_doc_len, k1=1.2, b=0.75):
idf = math.log(1 + (n_docs - df + 0.5) / (df + 0.5))
norm = tf + k1 * (1 - b + b * doc_len / avg_doc_len)
return idf * tf * (k1 + 1) / normThe full document score is the sum of this value over the query terms. Three parts do the work.
Smoothed idf
log(1 + (N - df + 0.5) / (df + 0.5)) is always positive. Older BM25 formulas could go negative for terms present in more than half the documents. Lucene uses the form above. Common terms get a score near zero instead of a penalty.
Term frequency saturation (k1)
The tf part is tf * (k1 + 1) / (tf + k1) when the document has average length. It rises quickly and then flattens toward k1 + 1. With k1 = 1.2 and an average-length document:
| tf | tf factor |
|---|---|
| 1 | 1.00 |
| 3 | 1.57 |
| 10 | 1.96 |
| 100 | 2.17 |
Going from 1 to 3 occurrences adds a lot. Going from 10 to 100 adds almost nothing, which blunts keyword stuffing. A higher k1 lets repeated terms keep helping for longer. A lower k1 saturates sooner.
Length normalization (b)
The factor 1 - b + b * doc_len / avg_doc_len scales the denominator by document length. With b = 0.75, a document twice the average length is penalized and a shorter one is boosted. Setting b = 0 turns length normalization off. Setting b = 1 applies it fully.
A worked example
Assume an index of 1000 documents with an average length of 100 terms. The query term appears in 10 documents.
import math
def bm25_term_score(tf, df, n_docs, doc_len, avg_doc_len, k1=1.2, b=0.75):
idf = math.log(1 + (n_docs - df + 0.5) / (df + 0.5))
norm = tf + k1 * (1 - b + b * doc_len / avg_doc_len)
return idf * tf * (k1 + 1) / norm
N, AVG = 1000, 100
# Same tf, different lengths
for doc_len in (50, 100, 200):
s = bm25_term_score(tf=3, df=10, n_docs=N, doc_len=doc_len, avg_doc_len=AVG)
print(f"len={doc_len:>3} score={s:.2f}")
# Same document, rare term vs common term
rare = bm25_term_score(tf=3, df=10, n_docs=N, doc_len=100, avg_doc_len=AVG)
common = bm25_term_score(tf=3, df=500, n_docs=N, doc_len=100, avg_doc_len=AVG)
print(f"rare={rare:.2f} common={common:.2f}")The output is:
len= 50 score=8.02
len=100 score=7.16
len=200 score=5.90
rare=7.16
common=1.09The same three occurrences score 8.02 in a short document and 5.90 in a long one. A term found in 10 documents is worth about six times as much as one found in half the index.
Where the score comes from in a search request
The analyzer must produce the same terms at query time as at index time. If it does not, the postings lookup finds nothing and there is nothing to score.
Ranking in practice
Scores are not comparable across queries
A BM25 score has no absolute meaning. A score of 12 for one query can be a poor match and a score of 4 for another can be an excellent one. Use scores to order results within one query. Do not use a fixed threshold like "show only results above 5" across queries.
Per-field scoring and boosts
Engines score each field separately. A match in a short title field naturally scores higher than the same match in a long description, because of length normalization. You can push this further with explicit boosts:
GET /products/_search
{
"query": {
"multi_match": {
"query": "running shoes",
"fields": ["name^3", "description"]
}
}
}Here name^3 multiplies that field's contribution by 3.
Filters do not score
In the bool query from the index design chapter, filter clauses only include or exclude documents. Only must and should clauses add to the score. Put exact conditions such as category or price range in filter. Doing so keeps the ranking about text relevance and lets the engine cache the filter results.
Statistics are per shard
Each shard computes idf from its own documents by default. On a large index with evenly spread documents, the shard statistics are close enough to the global ones. On a small index split across several shards, df and N can differ between shards, so identical documents may score differently. Two common fixes are to use fewer shards for small indexes and to request global statistics with search_type=dfs_query_then_fetch. The second option costs an extra round trip.
Deleted documents still count
Lucene keeps deleted documents in its segments until a merge removes them. Their terms still affect df and N until then. This causes small, temporary score changes after bulk deletes or updates and is not a bug.
Debugging a score
Ask the engine to explain itself instead of guessing. Adding "explain": true to a search request, or calling the explain API for one document, returns the breakdown of idf, tf, and length normalization for each term:
GET /products/_explain/42
{
"query": { "match": { "name": "running shoes" } }
}Common errors
- Tuning
k1andbfirst. The defaults (1.2 and 0.75) work for most text. Change them only after you have a way to measure the effect, as described in the relevance evaluation chapter. - Expecting exact-match ordering from a text field. A product named exactly
Running Shoesdoes not automatically beat a longer one. If you need that, add a boostedkeywordsubfield or ashouldclause on the exact value. - Sorting by a field and expecting relevance. If a request sorts by
price, the engine orders by price and the BM25 score no longer determines the order. - Stuffing business signals into text relevance. Popularity, recency, and stock status are not part of BM25. Combine them explicitly with a function score or a rescoring step, and keep their weights small enough that relevance still matters.
- Comparing scores between indexes. Different corpora give different idf values, so scores from different indexes cannot be compared directly.
Exercise
In an index of 1000 documents, term A appears in 5 documents and term B appears in 800. A document contains each term three times and has average length. Which term contributes more to its BM25 score, and which two parts of the formula explain the difference? Would the answer change if the document were three times the average length?
Show answer
Term A contributes more. Both terms have the same tf, the same length normalization, and therefore the same tf factor, so the difference comes entirely from idf. Term A is rare, so its idf is high. Term B is in 80% of the documents, so its idf is close to zero. Tripling the document length would reduce both contributions through the length-normalization part of the denominator, but it would not change which term contributes more, because idf is a separate multiplier that does not depend on document length.
Exercise
A product page repeats the word "sale" 60 times and ranks above a page that uses it 4 times, even though the second page is the better match. Which BM25 parameter controls how much repeated occurrences help, and what would you change? What else could you check first?
Show answer
The parameter is k1, which controls term frequency saturation. Lowering it makes the tf factor flatten sooner, so 60 occurrences gain little over 4. Before changing it, run the explain API on both documents. The stuffed page might rank higher because it is shorter (length normalization with b), because "sale" is boosted in a field, or because another query term matches only in that page. Change k1 only after confirming that tf is the cause, and measure the result against a set of judged queries.