When an AI assistant that answers from your documents gets something wrong, there are two suspects: the search that fetched the passages, and the model that wrote the answer from them. Check the search first, because if the right passage never arrived, no prompt can fix the answer. Retrieval metrics score one thing: whether the passages that answer a question came back, and how near the top. Here you’ll move answers up and down a list of results to see what each metric rewards, then compare four searches on a small test set.
Two places to fail#
A RAG system (retrieval-augmented generation) works in two steps. First it searches your documents for the passages most likely to help. Then it pastes the top few into the prompt and asks a language model to answer from them. Most teams tune the second step, the prompt, because it’s the visible one. But if the answer isn’t among the passages the model reads, it can only guess or say it doesn’t know.
So measure retrieval on its own. You need an evaluation set: questions, and for each one, the passages that answer it, marked by a person. The examples here use the Hearth help centre from the hybrid search explainer: 16 short passages about a made-up brand’s thermostats and doorbells, with 14 new questions and the 18 passages that answer them.
Five ways to score a list#
Every search returns a ranked list. The system passes the top k of them to the model, so k is how many passages the model gets to read. Each metric looks at that list differently:
- Hit rate@k: did at least one answer make the top k? 1 or 0.
- Recall@k: what share of all the answers made the top k?
- Precision@k: what share of the top k are answers?
- Reciprocal rank: 1 divided by the place of the first answer: 1 for first, 0.5 for second, 0.33 for third. Averaged over questions, it’s called MRR, mean reciprocal rank.
- nDCG@k (normalised discounted cumulative gain): every answer in the top k scores points, fewer the lower it sits, divided by the best score possible. 1 means every answer is as high as it can be.
Predict first
A search puts the right passage first, and you pass the top 5 to the model. The passage slips to third. Which score drops?
BGE puts the D2 recording passage first and the Hearth Plus passage fourth. With k at 5, both answers are in: hit rate, recall and reciprocal rank are all 1. Precision is only 0.40, because two answers can fill at most two of five slots. And nDCG is 0.88: the second answer counts for less in fourth place than it would in second.
Now drag k down to 3. The Hearth Plus passage falls below the line, and recall drops to 0.50: the model would be told about recording but not about the subscription that keeps the clips. Recall@k answers the question RAG cares about most: did the answer reach the model at all? The others say how well the list is ordered, which matters too, for reasons that come next.
Choosing k#
Raising k can only raise recall. Why not pass 50 passages every time? Three reasons. Every passage costs tokens, which means money and waiting time. Irrelevant passages can distract the model or lead it to mix sources. And models don’t read long prompts evenly: Nelson Liu and colleagues found in 2023 that models answered best when the useful passage was near the start or end of the prompt, and noticeably worse when it sat in the middle. So the order matters, and that’s what reciprocal rank and nDCG measure.
A practical approach: pick the k your budget allows, then make sure recall at that k is high, and use MRR or nDCG to break ties between searches.
Comparing four searches#
Now score whole searches across all 14 questions: keyword search (BM25), vector search with two embedding models, MiniLM and BGE small, and a hybrid that merges BGE with keyword search, counting each equally.
Predict first
Pass each search’s top 5 to the model. Which searches get every answer to every question in?
At k = 5, the three embedding searches get every answer in. Keyword search misses two questions completely: “the heating won’t come on” and “how can I cut my heating bill” share no useful word with the passages that answer them, which talk about “heat” and “temperature”, never “heating”.
Slide k down and the embedding searches separate, and the leader changes. At k = 1, MiniLM scores 0.86, which is the most possible here: four questions have two answers, and one slot can only hold one. The hybrid scores 0.79, BGE alone 0.68 and keyword search 0.61. At k = 2 the hybrid leads, 0.96 to MiniLM’s 0.93. At k = 4, BGE and the hybrid have every answer while MiniLM is still one short. Mixing keyword search into BGE fixes its two worst rankings, the E-147 error code (fourth to first) and the Wi-Fi question. Which search is best depends on your questions, your k and your metric, so measure it on your own data.
Look at the averages too. MRR ranges from 0.77 for keyword search to 1.00 for MiniLM, which put an answer first for every question. But averages can hide a single question that fails completely, which is exactly what users notice. The table of where each answer landed is often more useful than any average.
Building your own evaluation set#
- Start from real questions. Search logs, support tickets, what people asked in a pilot. 50 to 100 is a good start.
- Mark the answers. Run a few different searches, pool their top results, and have someone mark which passages answer each question. That’s how large search benchmarks like TREC have long gathered their labels. An LLM can mark them faster; check a sample of its work.
- Be wary of generated questions. Asking an LLM to write questions from each passage is cheap, but such questions tend to reuse the passage’s wording, which flatters keyword search.
- Mind the noise. With 14 questions, one question is 7 points of recall. Treat a difference of a question or two as luck, the same lesson as in A/B testing.
- Re-run it on every change: chunk size, embedding model, k, hybrid weight. That’s the point of having it.
Retrieval or generation?#
Once you can measure retrieval, a wrong answer becomes a quick diagnosis. Look at what the model was given.
- The answer wasn’t in the top k: it’s a retrieval problem. Try better chunking, a different embedding model, hybrid search, a larger k, or a reranker that re-orders the top results.
- The answer was there, but the reply was wrong: it’s a generation problem. Look at the prompt, the model, how many distracting passages came with it, and where in the prompt the answer sat.
In code#
The three most useful metrics in plain Python, averaged over three questions:
import math
def recall_at_k(retrieved, relevant, k):
return len(set(retrieved[:k]) & relevant) / len(relevant)
def reciprocal_rank(retrieved, relevant):
for place, doc in enumerate(retrieved, start=1):
if doc in relevant:
return 1 / place
return 0.0
def ndcg_at_k(retrieved, relevant, k):
dcg = sum(1 / math.log2(place + 1) for place, doc in enumerate(retrieved[:k], start=1) if doc in relevant)
ideal = sum(1 / math.log2(place + 1) for place in range(1, min(k, len(relevant)) + 1))
return dcg / ideal
# For each question: what the retriever returned, in order, and the passages that answer it
results = [
(["d2-recording", "d3-power", "d2-battery", "hearth-plus", "p1-plug"], {"d2-recording", "hearth-plus"}),
(["screen-dark", "boiler", "offline", "weak-signal", "e-503"], {"boiler"}),
(["schedules", "eco-mode", "weak-signal", "p1-plug", "returns"], {"schedules", "eco-mode"}),
]
k = 3
print(f"recall@{k}: {sum(recall_at_k(r, rel, k) for r, rel in results) / len(results):.3f}")
print(f"MRR: {sum(reciprocal_rank(r, rel) for r, rel in results) / len(results):.3f}")
print(f"nDCG@{k}: {sum(ndcg_at_k(r, rel, k) for r, rel in results) / len(results):.3f}")
# recall@3: 0.833
# MRR: 0.833
# nDCG@3: 0.748In a real project, retrieved comes from your search function and relevant from your evaluation set. Libraries such as ranx compute these and more, with significance tests to tell real differences from luck.
What to remember
- Test retrieval on its own, with questions and the passages that answer them, before tuning prompts.
- Recall@k says whether the answers reached the model; MRR and nDCG say how near the top they came.
- Compare searches on your own questions at the k you’ll use, and read the per-question failures, not just the averages.