Highlights

Contents

Part IV
04

Ranking: TF-IDF and BM25

We give matching documents a comparison score. Raw word counts reward repetition and ignore whether a word is common. We will derive TF-IDF intuition, BM25 saturation, length normalization, and field-aware ranking.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Search basics: why LIKEfails2Tokenization and analysis3The inverted index4Ranking: TF-IDF and BM255The indexing pipeline6Shards and replicas7Autocomplete and fuzzysearch8Operating a searchcluster9Case study: search end toend

#Section 13Rare terms carry more evidence

Every report could contain match, while only a few contain a team name. Matching the team name tells us more about the user’s intent. Document frequency counts how many documents contain a term. Inverse document frequency, or IDF, gives rarer terms more weight.

A simple TF-IDF variant uses log⁡(N/df)\log(N/df), where NN is the number of documents and dfdf is document frequency. Read that as the logarithm of collection size divided by the number of documents using the term. In our corpus, red appears in 2 of 4 documents, giving log⁡(4/2)=0.693147\log(4/2)=0.693147. A term appearing in all documents would receive zero under this particular variant.

RARER TERMS RECEIVE A LARGER NATURAL-LOG TF-IDF WEIGHTRARER TERMS RECEIVE A LARGER NATURAL-LOG TF-IDF WEIGHT1.386294bluedf 1 / 40.693147reddf 2 / 40.287682birddf 3 / 40.000000all docsdf 4 / 4weight = ln(collection size / document frequency)
Figure 15.13Computed values for the stated natural-log TF-IDF variant. Different variants use different smoothing.

TF-IDF combines term frequency inside a document with inverse document frequency across the corpus. It is a family of formulas rather than one uniquely specified score. State normalization and smoothing before comparing numbers. Rarity measures discrimination under the text representation, not factual accuracy or trustworthiness.

#Section 14BM25 limits the benefit of repetition

Document 4 repeats bird, while documents 1 and 2 use it once. Rewarding repetition linearly lets a spammer repeat a term until a poor document dominates. BM25 is a relevance scoring family that gives diminishing returns for repetition and adjusts for document length.

For one term, use this stated illustrative form:

s=log⁡(1+N−df+0.5df+0.5)tf(k1+1)tf+k1(1−b+bℓ/ℓ‾).s=\log\left(1+\frac{N-df+0.5}{df+0.5}\right)\frac{tf(k_1+1)}{tf+k_1(1-b+b\ell/\overline{\ell})}.

Read the first factor as a smoothed rarity weight. The second factor rewards term frequency tftf while its denominator grows with frequency and a length adjustment. Here k1k_1 controls saturation, bb controls the strength of length normalization, ℓ\ell is document length, and ℓ‾\overline{\ell} is average document length. These are named tuning values, not measured truths about language.

All four tiny reports have length 3, so average length is 3. With k1=1.2k_1=1.2 and b=0.75b=0.75, the length term becomes 1. For bird, df=3df=3 gives IDF 0.3566750.356675. One occurrence contributes 0.3566750.356675, while two contribute 0.4904280.490428. Doubling occurrences increases the score by less than a factor of two.

BM25 GIVES DIMINISHING RETURNS FOR REPEATING BIRDBM25 GIVES DIMINISHING RETURNS FOR REPEATING BIRDterm frequencyscorelimit 0.78468502468tf 1: 0.356675tf 2: 0.490428k₁ = 1.2; equal document lengths; score is not a probability
Figure 15.14Computed BM25 values, rounded to six decimals for the stated four-document corpus and parameters.

Lucene's BM25 API documents its parameter meanings and IDF form. Scores in this chapter are calculated with the explicit formula above, so they can be reproduced independently of a deployed engine version.

#Section 15Length normalization compares context

A long report has more opportunities to mention bird once than a short title does. BM25's length adjustment counters that tendency. For a document twice the corpus average length, the adjustment is 1−0.75+0.75×2=1.751-0.75+0.75\times2=1.75. The denominator grows, reducing the same term-frequency contribution.

This correction is an assumption about how length relates to relevance. A long match report may be useful precisely because it explains more. Setting bb close to zero reduces the length penalty. Setting it close to one makes the document-to-average length ratio more influential. Tune using representative judgments, not a claim that a parameter is universally optimal.

THE SAME TERM COUNT CONTRIBUTES LESS IN A LONGER DOCUMENTTHE SAME TERM COUNT CONTRIBUTES LESS IN A LONGER DOCUMENT3 termsadjust 1bird: 0.3566756 termsadjust 1.75bird: 0.2531241 − 0.75 + 0.75 × 2 = 1.75 length adjustment
Figure 15.15Computed length adjustment for the explicitly chosen illustrative parameter b=0.75.

A multi-term score commonly sums the contributions from matched terms. For document 1 and query red bird, the stated formula gives 0.693147+0.356675=1.0498220.693147+0.356675=1.049822. This arithmetic is meaningful only under the stated term statistics and query construction. Query boosts, field normalization, and implementation choices can change a real engine's result.

#Section 16Relevance needs evaluation

Suppose the search returns five reports and a human judges three useful. Four useful reports exist in the collection for that question. Precision is useful returned results divided by all returned results, here 3/5=0.63/5=0.6. Recall is useful returned results divided by all useful results, here 3/4=0.753/4=0.75.

Changing an analyzer can increase recall by finding variants, but may reduce precision by merging unrelated meanings. A ranking change can move useful reports upward without changing membership. Keep a judged query set with difficult names, common words, spelling errors, and private content. A click log is informative but biased by what users were shown and where it appeared.

PRECISION COUNTS THE RETURNED SET; RECALL COUNTS ALL USEFUL DOCUMENTSPRECISION COUNTS THE RETURNED SET; RECALL COUNTS ALL USEFUL DOCUMENTSfive returned reportsrank 1usefulrank 2usefulrank 3usefulrank 4not usefulrank 5not usefulprecision 3 / 5 = 0.6recall 3 / 4 = 0.75one further useful report was not returnedillustrative human judgments, not inferred document quality
Figure 15.16Computed illustrative retrieval metrics. Relevance judgments are declared labels, not inferred truth.

NDCG, normalized discounted cumulative gain, evaluates graded usefulness with more credit for earlier ranks and normalization against an ideal ordering. State the gain convention before calculating it. The study script records rank discounts, but we do not manufacture a quality score without a judged result ordering.