Sub topic 4
Ranking results with TF-IDF and BM25
This chapter assumes you know what an inverted index is and how text analysis turns raw text into terms. It also assumes basic comfort with logarithms and Python. Here you will learn how a search engine decides which matching document comes first.
Why matching is not enough
An inverted index tells you which documents contain the query terms. It does not tell you which ones are the best answers. A query for "running shoes" may match thousands of products. Ranking assigns each match a numeric score, and the engine sorts results by that score.
Good scoring rests on three observations:
- A term that appears often in a document suggests the document is about that term.
- A term that appears in nearly every document says little. Words like "the" or "product" are weak signals.
- A long document contains more words by chance, so a raw count favors long documents unfairly.
TF-IDF
TF-IDF combines the first two observations.
- Term frequency (tf) is how many times the term appears in one document.
- Document frequency (df) is how many documents contain the term.
- Inverse document frequency (idf) grows as df shrinks. Rare terms get a high idf.
The classic score for a term in a document is tf multiplied by idf. For a multi-term query, the engine adds the per-term scores.
TF-IDF has two weaknesses. Raw tf grows without limit, so a document that repeats a word 50 times beats one that uses it 5 times by a wide margin. It also has no built-in handling of document length.
BM25
BM25 is the default scoring function in Elasticsearch, OpenSearch, and Lucene-based engines. It keeps the idf idea and fixes both weaknesses.
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 function has two parts:
idfis the rarity weight. The+ 0.5smoothing avoids division by zero when df is 0 or equalsn_docs.normand the fraction around it dampen tf and adjust for length.
Two parameters control the behavior:
| Parameter | Default | Effect |
|---|---|---|
| `k1` | 1.2 | How quickly extra occurrences stop helping. Higher values let tf keep raising the score for longer. |
| `b` | 0.75 | How strongly length is penalized. 0 ignores length. 1 normalizes fully against the average. |
A worked comparison
Suppose a catalog has 1,000 documents with an average length of 10 terms. The query term "shoes" appears in 50 of them.
short = bm25_term_score(tf=2, df=50, n_docs=1000, doc_len=5, avg_doc_len=10)
long_ = bm25_term_score(tf=2, df=50, n_docs=1000, doc_len=40, avg_doc_len=10)
many = bm25_term_score(tf=8, df=50, n_docs=1000, doc_len=5, avg_doc_len=10)
print(round(short, 2), round(long_, 2), round(many, 2))Include the function from above in the same file. The short document scores higher than the long one with the same tf, because the term makes up a larger share of it. Quadrupling tf from 2 to 8 raises the score, but by much less than four times. That is the saturation effect.
Practical points for system design
- You rarely implement BM25 yourself. The engine computes it from statistics stored in the index.
- idf depends on corpus statistics. In a sharded index, each shard has its own df and document counts by default, so scores can differ slightly between shards on small or uneven data.
- Scoring is per field. A match in a short
namefield and a match in a longdescriptionfield are scored separately, and you can weight them with boosts in the query. - Analysis affects scores. Stemming merges "shoe" and "shoes" into one term, which changes df and tf.
- Filters do not score. Exact-match conditions on keyword fields belong in a filter clause so they restrict results without changing the order.
Exercise
A document has the query term 3 times and is 100 terms long, while the average is 20 terms. A second document has the term 3 times and is 20 terms long. Which scores higher under BM25 with default settings, and which parameter controls the difference?
Show answer
The 20-term document scores higher. With equal tf, the longer document gets a larger norm value, which lowers its score. The parameter b controls how strongly document length is penalized.
Exercise
Why does BM25 give a diminishing return for repeated terms, and which parameter sets how fast that happens?
Show answer
The tf factor tf * (k1 + 1) / (tf + k1 * ...) approaches a ceiling as tf grows, so each extra occurrence adds less. The parameter k1 sets how quickly the ceiling is reached.