Sub topic 13
Measuring retrieval quality: recall@k, MRR, and nDCG
This chapter assumes you can run the search code from the earlier chapters, meaning you can embed documents and queries and get a ranked list back. You also need basic Python and comfort with averages and logarithms. It covers how to tell whether that ranked list is any good, and how to compare two retrievers with numbers instead of impressions.
Why you need a number
A semantic search system rarely fails loudly. It returns plausible results for every query, so a regression in chunking, model choice, or index settings can go unnoticed. Typing five queries and eyeballing the output does not scale, and it misses regressions on queries you did not think to try.
Retrieval evaluation replaces that with a repeatable procedure: a fixed set of queries with known relevant documents, a retriever that produces ranked lists, and metrics that score those lists. You can then change one thing, rerun, and see whether the score moved.
Building the labeled set
An evaluation set has two parts.
- A list of queries, ideally written or sampled from real user traffic.
- Relevance judgments (often called qrels) that say which documents answer each query.
Judgments come in two forms. Binary judgments mark each document as relevant or not. Graded judgments use a small scale such as 0 (irrelevant), 1 (partially relevant), 2 (highly relevant). Recall and MRR need only binary labels. nDCG uses grades when you have them.
Practical guidance:
- 50 to 200 queries is a workable starting size. Fewer than that makes differences between systems hard to trust.
- Cover the query types you expect: short keyword-like queries, full questions, rare terms, and queries with no good answer.
- Judge at the same level the retriever returns. If you index chunks, either label chunks or map each chunk back to its source document and score at the document level.
- Keep the evaluation queries out of any data you used to fine-tune or tune the system.
Recall@k
Recall@k asks what share of the relevant documents appear in the top k results.
recall@k = (relevant documents in the top k) / (all relevant documents)
If a query has four relevant documents and two of them appear in the top 5, recall@5 is 0.5. Recall suits any stage whose job is to not lose good candidates, such as the first-stage retrieval that feeds a reranker or a language model. Pick k to match how many results the next stage actually consumes.
Edge cases:
- If a query has more than k relevant documents, recall@k cannot reach 1.0. With 10 relevant documents and k=5, the best possible value is 0.5. Interpret the number against that ceiling, or use a related metric such as hit rate (did at least one relevant document appear?).
- If a query has no relevant documents, recall is undefined. The code below returns 0.0, but you should usually exclude such queries from the average, or evaluate them separately as "should return nothing useful" cases.
- Recall ignores order inside the top k. A relevant document at rank 1 and at rank k count the same.
Mean reciprocal rank
Reciprocal rank looks only at the first relevant result. If it sits at rank r, the score is 1/r: 1.0 for rank 1, 0.5 for rank 2, 0.333 for rank 3, and 0.0 if no relevant document appears. Averaging over all queries gives mean reciprocal rank (MRR).
MRR fits tasks where the user wants one good answer and stops reading after finding it, such as question answering or a "best match" lookup. It is a poor fit when users need several relevant results, because it ignores everything after the first hit. It also drops steeply: moving the first hit from rank 1 to rank 2 costs 0.5, while moving it from rank 9 to rank 10 costs about 0.011.
nDCG
Normalized discounted cumulative gain (nDCG) handles graded relevance and rewards putting the best documents first. It is built in three steps.
- Gain. Each result contributes its relevance grade.
- Discount. A result at rank i is divided by log2(i + 1), so rank 1 counts fully, rank 3 counts half, and lower ranks count progressively less. Summing gives the discounted cumulative gain, DCG@k.
- Normalize. Divide by the DCG@k of the ideal ordering (all documents sorted by grade, best first). The result lies between 0 and 1, where 1 means the ranking matches the ideal.
Normalizing makes scores comparable across queries that have different numbers of relevant documents. Some libraries use the gain 2^grade − 1 instead of the raw grade, which rewards top-grade documents more strongly. Both are valid. Use one convention consistently and check which one a library uses before comparing your numbers with someone else's.
| Metric | Uses grades | Sensitive to order | Best for |
|---|---|---|---|
| recall@k | No | No (inside top k) | First-stage retrieval, candidate generation |
| MRR | No | Yes, first hit only | Single-answer lookup, question answering |
| nDCG@k | Yes | Yes, whole top k | Ranked result lists with varying usefulness |
Implementing the metrics
The code below implements all three metrics and an evaluation loop that averages them over queries. It has no dependencies beyond the standard library. The small example is worked by hand in the comments so you can check it.
import math
def recall_at_k(retrieved, relevant, k):
"""retrieved: ranked list of ids; relevant: set of ids judged relevant."""
if not relevant:
return 0.0
hits = len(set(retrieved[:k]) & relevant)
return hits / len(relevant)
def reciprocal_rank(retrieved, relevant):
for rank, doc_id in enumerate(retrieved, start=1):
if doc_id in relevant:
return 1.0 / rank
return 0.0
def dcg_at_k(gains, k):
return sum(g / math.log2(i + 1) for i, g in enumerate(gains[:k], start=1))
def ndcg_at_k(retrieved, grades, k):
"""grades: dict mapping doc id to a relevance grade (missing means 0)."""
gains = [grades.get(d, 0) for d in retrieved]
ideal = sorted(grades.values(), reverse=True)
idcg = dcg_at_k(ideal, k)
if idcg == 0:
return 0.0
return dcg_at_k(gains, k) / idcg
def evaluate(run, qrels, k):
"""run: query id -> ranked list of doc ids.
qrels: query id -> {doc id: grade}. Grade > 0 counts as relevant."""
recalls, rrs, ndcgs = [], [], []
for qid, grades in qrels.items():
relevant = {d for d, g in grades.items() if g > 0}
if not relevant:
continue # skip queries with no relevant documents
retrieved = run.get(qid, [])
recalls.append(recall_at_k(retrieved, relevant, k))
rrs.append(reciprocal_rank(retrieved, relevant))
ndcgs.append(ndcg_at_k(retrieved, grades, k))
n = len(recalls)
return {
f"recall@{k}": sum(recalls) / n,
"MRR": sum(rrs) / n,
f"nDCG@{k}": sum(ndcgs) / n,
}
qrels = {
"q1": {"d1": 2, "d2": 1},
"q2": {"d5": 1},
}
run = {
"q1": ["d4", "d1", "d9", "d2"],
"q2": ["d5", "d3", "d8", "d6"],
}
for name, value in evaluate(run, qrels, k=3).items():
print(f"{name}: {value:.3f}")
# recall@3: 0.750 q1 = 0.5 (d2 is at rank 4), q2 = 1.0
# MRR: 0.750 q1 = 0.5 (first hit at rank 2), q2 = 1.0
# nDCG@3: 0.740 q1 = 1.262 / 2.631 = 0.480, q2 = 1.0For q1, the DCG@3 is 2 / log2(3) = 1.262 because only d1 (grade 2) appears at rank 2. The ideal ordering gives 2 / 1 + 1 / log2(3) = 2.631. Dividing gives 0.480.
To run this against your search code from earlier chapters, build run by calling your search function once per query and collecting document ids. Map chunk ids to document ids first if you indexed chunks, and remove duplicates while keeping the first occurrence. Otherwise two chunks of one document fill two slots in the top k and distort every metric.
Reading the numbers
Averages hide a lot, so a few habits help.
- Compare systems on the same queries and the same k. A recall@10 from one set cannot be compared with a recall@5 from another.
- Look at per-query scores, not only the mean. Sort queries by score and read the worst ten. This usually reveals a cause such as a missing prefix, a bad chunk boundary, or a vocabulary gap that suits hybrid search.
- With a small query set, differences of 0.01 to 0.02 are noise. Use a paired comparison: score both systems per query, then bootstrap the differences or run a paired test before claiming an improvement.
- Labels are usually incomplete. If the retriever surfaces a relevant document nobody labeled, it is scored as a miss. Spot-check the top results of the best system and add missing labels, otherwise you will tend to reward systems similar to the one that produced the labels.
- Match the metric to the decision. Use recall@k to tune first-stage retrieval, then nDCG or MRR on the final ranking after reranking.
You can apply the same machinery to approximate indexes. Treat the exact search result as the "relevant" set and compute recall@k of an HNSW or IVF index against it. This measures how much accuracy the approximation costs, separately from how good the embedding model is.
Summary of decisions
- Use recall@k when the retriever feeds another stage and missing a relevant document is the main risk.
- Use MRR when users want one correct answer quickly.
- Use nDCG@k when you have graded labels or care about the order of the whole list.
- Evaluate at the document level, deduplicate results, skip queries without relevant documents, and compare systems with paired per-query scores.
Exercise
A retriever returns ["d2", "d7", "d1", "d5"] for a query whose relevant set is {"d1", "d5", "d9"}. Compute recall@3, recall@4, and the reciprocal rank.
Show answer
The top 3 results contain only d1 from the relevant set, so recall@3 = 1/3 = 0.333. The top 4 contain d1 and d5, so recall@4 = 2/3 = 0.667. The first relevant document (d1) is at rank 3, so the reciprocal rank is 1/3 = 0.333.
Exercise
A query has 8 relevant documents. What is the highest recall@5 any retriever can achieve, and why does this matter when you compare recall@5 across queries?
Show answer
The highest possible value is 5/8 = 0.625, because only five documents fit in the top 5. Queries with many relevant documents therefore cap the average below 1.0 even for a perfect system. Interpret recall@k against that ceiling, or choose k at least as large as the typical number of relevant documents.
Exercise
Two systems have the same recall@10 but system A has nDCG@10 of 0.82 and system B has 0.55. What does the difference tell you, and which metric would you check next if users read only the first result?
Show answer
Both systems find the same share of relevant documents in the top 10, but A ranks the more relevant ones higher, because nDCG discounts hits at lower ranks and uses the grades. If users read only the first result, check MRR (or precision at 1), since it measures how early the first relevant document appears.