TF-IDF, BM25, cosine similarity, RRF and NDCG
TF-IDF, BM25, cosine similarity, reciprocal rank fusion, and NDCG are core concepts in retrieval, search engines, and ranking evaluation.
Matching vs ranking
A search runs in two steps (AI-Powered Search, §3.2.4):
- Matching. Filter the index down to the pages that can be answers. Yes or no, no score.
- Ranking. Score every match and sort, best first. The rest of this note is about this step.
Matching is largely a speed-up in that scoring a few hundred matches is vastly cheaper than scoring every page. It also provides you with result counts and facets.
The query's logic decides what matches. For the words connection, reset, and error:
| Query | Matches |
|---|---|
"connection reset error" | Only the exact phrase |
connection AND reset AND error | Pages with all three words, anywhere |
| At least 2 of the 3 words | Pages with any two of them |
connection OR reset OR error | Pages with any one of them; BM25 ranks pages with more of the words higher |
Filters and the query do different jobs (§3.2.6). A filter, such as category = docs, only removes pages. The query removes pages and also scores the remaining ones.
Try: try each match mode, then add the filter
3 of 8 pages match · ranked by BM25, best first
Show the pages
- 1Changelog 4.2blog · 1.73
Fixed a connection reset error when uploads stalled.
- 2Network error codesdocs · 1.63
Each error code has a page: timeout error, refused connection, reset by peer.
- 3ECONNRESET in Nodedocs · 1.52
A connection reset error means the server closed the connection. Retry the request and check the server logs for the error.
- Reset your password
- Connection pooling
- Error handling
- Router drops Wi-Fi
- Contact support
TF-IDF and BM25
| TF-IDF · idf × raw tf | BM25 · idf × capped tf ÷ length |
|---|---|
| Repeats never plateau — 50 mentions ≠ 50× relevant | Saturation — Controlled by k1 |
| Long docs win by default — More words, more matches | Length normalization — Controlled by b |
BM25 by example
Someone's been going through your docs for ECONNRESET. One page has it 5 times and is twice the length of the average page. Every individual component of BM25 has its own take on what value to assign to those 5 occurrences.
- TF (term frequency). The page has
ECONNRESET5 times. TF-IDF would give that a value of 5. - idf — rarity. An error code that appears on very few pages is worth more than a fairly common word like 'connection'. It's a multiplier so the chart below doesn't include it.
- k1 — saturation. Caps what the repeats are worth. At k1 = 1.2 the weight can never go above k1 + 1 = 2.2.
- b — Length penalty. A long page has more chances to repeat any word. At b = 0.75 this page scores 13% less than an average-length page with the same 5 mentions.
Try: set k1 to 3, then b to 0
weight at tf = 5: 5 × 2.2 / (5 + 1.2 × (1 − 0.75 + 0.75 × 2.00)) = 1.55
- Start. BM25 gives the 5 mentions a weight of 1.55. Raw tf would give 5.
- Follow the "BM25, this doc" line to tf = 20. Four times the mentions but the weight only gets to 1.99, just under the 2.2 ceiling.
- Set k1 to 3. The repeats will obviously carry on for longer. The ceiling goes to 4.0 and the weight at 5 comes in at 1.95.
- Then set b to 0. Page length doesn't matter any more. This page and an average length page are now both worth 2.50.
Lucene, and with it Elasticsearch, OpenSearch and Solr, omit the k1+1 on top of the fraction (AI-Powered Search, §3.2.1). Each weight is reduced by the same factor, the ranking is unchanged and the ceiling becomes 1.
- Default to BM25 for lexical search. It's the baseline in Elasticsearch, OpenSearch, Lucene and pretty much all the RAG stacks out there. Plain old TF-IDF is now really just a teaching exercise or a very cheap feature.
- Use it in conjunction with embeddings rather than as a replacement for them. BM25 is going to win on exact matches (IDs, error codes, names, specialist jargon etc.). The dense retrievers are going to win on paraphrase and on meaning. The current state of the art is hybrid retrieval (BM25 plus embeddings, combined via RRF) followed by a reranker.
- Tuning is mostly relevant for short or very uneven length documents. Start with
k1 ≈ 1.2andb ≈ 0.75and then tune on a small labelled set rather than trying to guess.
Boosting: plus vs times
Popular pages obviously do need a lift. The book looks at two ways of doing this (§3.2.3) with a popularity score from 0 to 1:
- Plus. score = BM25 + w × popularity
- Times. score = BM25 × (1 + w × popularity). The book's own example multiplies by 10 × popularity; the 1 + ensures that a page with zero popularity doesn't get scored at zero.
Two searches, two pages. The error code list wins out in terms of matching; the troubleshooting guide is the more popular of the two. The rare word ECONNRESET gets huge BM25 scores and the common word 'connection' gets very small ones: same ratio, just a tenth of the size.
Try: raise the boost weight to 1
Show the rankings
- 1. Error code list12 → 12.10
- 2. Troubleshooting guide9 → 9.45
- 1. Troubleshooting guide0.9 → 1.35
- 2. Error code list1.2 → 1.30
- 1. Error code list12 → 13.20
- 2. Troubleshooting guide9 → 13.05
- 1. Error code list1.2 → 1.32
- 2. Troubleshooting guide0.9 → 1.30
- Start (w = 0.5). Times: Error code list wins both searches. Plus: it wins on ECONNRESET (12.10 v 9.45) but loses on connection (1.30 v 1.35). The same added boost more than makes up for the very modest scores of a common word.
- Raise w to 1. Times: the troubleshooting guide now wins both searches so the two searches still agree. Plus: they still disagree.
A multiplied boost affects every search in exactly the same way. An added boost has to be scaled to the scores it's being added to and those scores will vary from search to search. The book's warning on the other side is that if you push a multiplied boost too high it will swamp relevance.
Cosine similarity
Cosine similarity looks at the direction of two vectors and ignores their length. The dot product does the multiplying out so length does count.
- Sparse vectors. TF-IDF and BM25 give every word its own slot so almost every slot is zero. In the book's apple juice example two very short documents require 48 slots and the query 2. The engines only store the non-zero ones (§3.1.3).
- Dense vectors. The embeddings have hundreds of slots all filled in. No one slot represents a word; the meaning is encoded in the collective of the slots (§13.1).
cos(q, d) = (q · d) / (|q| × |d|)
q · d = Σi qi × di
- Direction. Cosine asks only whether a document uses the query's words in the same proportions.
- Length. The dot product also grows when a document repeats those words more often.
The example from AI-Powered Search (§3.1): the query “apple juice” against two documents. Doc 1 is a lunch order that mentions apple juice once. Doc 2 is a product page that says apple 3 times and juice 4 times.
Try: set Doc 2 · apple to 4
Show the numbers
| Cosine | Angle | Dot product | |
|---|---|---|---|
| Doc 1 | 1.00 | 0° | 2 |
| Doc 2 | 0.99 | 8° | 7 |
cos(query, Doc 2) = (1×3 + 1×4) / (1.41 × 5.00) = 0.99
- Start. Doc 1 is a perfect match in terms of the query proportions (cosine 1.00, dot product 2). Doc 2 is slightly less good (cosine 0.99, dot product 7). Cosine gives us Doc 1 first, the dot product gives us Doc 2 first.
- Set Doc 2 · apple to 4. Now Doc 2 has the query's proportions as well so cosine is at 1.00 and the dot product is up to 8.
- Set Doc 2 · apple to 0 and juice to 5. Doc 2 drops "apple" completely. Cosine drops to 0.71 but the dot product still favours it (5 to 2). Raw repetition wins again, the same issue that BM25 caps with k1.
Vector search engines normally scale all the vectors to length 1 first. The dot product then becomes the cosine and it's a lot faster to compute (AI-Powered Search, §13.2).
Hybrid search
Hybrid search runs BM25 and a vector search side by side, then merges the two result lists. The book walks through three ways to merge and notes there are many more (§15.5):
- Reciprocal rank fusion (RRF). Uses only each page's place in each list.
- Relative score fusion (RSF). Rescales each list's scores to 0–1, then takes a weighted average.
- Match first, rerank second. BM25 decides which pages qualify, then the vector score reorders them. Exact matches are guaranteed, and meaning sets the order.
Reciprocal rank fusion
BM25 scores and vector scores are on different scales, so RRF ignores them and uses only the ranks.
RRF(d) = Σlists 1 / (k + rank(d))
- Each list votes. A page earns 1 / (k + rank) from every list it appears in.
- Agreement wins. A page high in both lists beats a page that tops only one.
- k sets the curve. A small k makes first place count much more. AI-Powered Search uses k = 60 (§15.5.1).
Back to the ECONNRESET search. BM25 finds the exact error code; the vector search finds pages about connections being reset.
Try: switch to RSF, then move the weight
Show the numbers
- 1Error code list14.2
- 2Changelog 2.49.8
- 3Socket errors9.1
- 4Retry policy7.5
- 5Proxy setup3.0
- 1Connection resets0.90
- 2Socket errors0.86
- 3Retry policy0.84
- 4Timeouts0.81
- 5Error code list0.80
- 6Load balancer FAQ0.70
- 1Socket errors1/63 + 1/62 = 0.0320
- 2Error code list1/61 + 1/65 = 0.0318
- 3Retry policy1/64 + 1/63 = 0.0315
- 4Connection resets1/61 = 0.0164
- 5Changelog 2.41/62 = 0.0161
- 6Timeouts1/64 = 0.0156
- 7Proxy setup1/65 = 0.0154
- 8Load balancer FAQ1/66 = 0.0152
RRF(Socket errors) = 1/63 + 1/62 = 0.0320
- Start. Socket errors comes out on top, though neither list ranked it first: 3rd and 2nd beat 1st and 5th.
- Set k to 1. First place now counts much more. Error code list takes the lead, and Connection resets, first in only one list, climbs to 3rd.
Relative score fusion
RSF keeps the scores but rescales them: in each list the best score becomes 1 and the worst becomes 0. A weight w then decides how much BM25 counts against the vector search.
RSF(d) = w × BM25′(d) + (1 − w) × vector′(d)
Switch the widget above to RSF:
- Switch to RSF. Error code list takes first. Its BM25 score of 14.2 is far ahead of the next one (9.8), and RSF counts that gap; RRF only saw “1st”.
- Set w to 0.2. The vector search now decides most of the score, and Connection resets, which BM25 never found, takes first.
- The catch. The last page in each list scores 0, however close it was to the others. RSF depends on how the scores are spread; RRF does not.
NDCG
Normalized Discounted Cumulative Gain (NDCG) is a key metric used to measure the quality and effectiveness of ranking and search engine algorithms.
| What NDCG Measures | The Three Calculation Steps |
|---|---|
| Relevance — Grades from 0 = irrelevant to 3 = perfect | Gain — 2rel − 1 points per result |
| Position — Results near the top count more | Discount — Divide by log₂(rank + 1) |
| Normalization — Scores from 0 to 1, comparable across queries | Normalize — Divide by the best possible order (IDCG) |
DCG@k = Σi=1k (2reli − 1) / log₂(i + 1)
NDCG@k = DCG@k / IDCG@k
| Rank | 1 | 2 | 3 | 4 | 5 | 10 |
|---|---|---|---|---|---|---|
| Counts | 100% | 63% | 50% | 43% | 39% | 29% |
NDCG by example
Each letter in the name is one step:
- G — Gain. Points for one result, set by its grade: 2rel − 1. Doc B (grade 3) earns 7; Doc C (grade 0) earns nothing.
- C — Cumulative. Add up the points of every result in the top k.
- D — Discounted. Shrink each result's points by its position. Doc B's 7 points are worth 4.42 at rank 2.
- N — Normalized. Divide by the score of the perfect order. 6.71 out of a possible 13.35 is 0.50.
- @k — Cutoff. Only the top k results count. With k = 5, Doc F at rank 6 adds nothing.
Reorder the list below and watch the three numbers move:
Try: press Ideal order, then move Doc F up
- 1Doc Arel 11 × 1.00 = 1.00
- 2Doc Brel 37 × 0.63 = 4.42
- 3Doc Crel 00 × 0.50 = 0.00
- 4Doc Drel 23 × 0.43 = 1.29
- 5Doc Erel 00 × 0.39 = 0.00
- 6Doc Frel 3outside top 5
NDCG@5 = 0.50 · show the numbers
NDCG@5 = 6.71 / 13.35 = 0.50
- Start. The top 5 add up to DCG@5 = 6.71. Doc F sits at rank 6, so its 7 points don't count.
- Press Ideal order. Both grade-3 documents move to the top. That is the best possible score, IDCG@5 = 13.35, so NDCG@5 is 1.00.
- Press Reset, then move Doc F up once. It enters the top 5. Its 7 points now count at 0.39: DCG@5 rises to 9.42 and NDCG@5 jumps from 0.50 to 0.71.
- Close to 1. The best results sit at the top.
- Close to 0. The best results are buried or missing.
- Tune BM25 with it. NDCG@10 is the standard headline metric (BEIR reports it). Grid-search
k1andbon a small labeled set and keep the pair that maximizes it. - Pair it with recall@k. If the first-stage retriever feeds a reranker or an LLM, recall@50 or @100 tells you whether the relevant documents are in the candidate pool at all. NDCG@10 tells you whether the final order is good.
- IDCG uses all judged documents for the query, not just the ones you retrieved. A relevant document you never surfaced still lowers your score, as it should.
- Unjudged documents count as irrelevant. A new system that surfaces good but unlabeled documents gets penalized unfairly, so check how much of each top-10 is actually judged.
- Libraries differ. Some use linear gain (
rel) and others use2rel − 1, so numbers aren't comparable across tools until you check. - The trend is LLM-generated relevance labels for building graded test sets cheaply. Calibrate them against a human-labeled sample and check agreement (e.g., Krippendorff's alpha) before trusting NDCG deltas.