RAG Evaluation: Metrics for Retrieval and Generation Quality › Evaluating the Retrieval Component

Michael BrenndoerferJanuary 13, 202520 min read
Language AI HandbookAll chapters
Part 44 of 67Retrieval-Augmented Generation
Chapter 345RAG Evaluation: Metrics for Retrieval and Generation Quality › Evaluating the Retrieval Component
Reading section 2 of 11 · Evaluating the Retrieval Component · 20 minSection 2 of 11 · 20 min

Book contents

Section 2 of 11 · 20 min read

RAG Evaluation: Metrics for Retrieval and Generation Quality › Evaluating the Retrieval ComponentOne section · Sections in this chapter2 / 11 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

The retrieval stage determines the evidence available to the generator. Dense retrieval, as we covered in earlier chapters, encodes queries and documents into a shared vector space and uses similarity metrics like cosine similarity to find nearest neighbors. But geometric similarity in embedding space does not guarantee semantic relevance for the specific query at hand. A document about a related topic might be a close neighbor without containing the specific information needed. Evaluation metrics for retrieval must account for both whether relevant items appear in the result set and where they appear, since generators typically have limited context windows.

Understanding retrieval performance is foundational because it establishes an upper bound on system capability. If the retrieval component fails to fetch documents containing the answer, even the most advanced generator cannot produce a correct response. This asymmetry matters enormously in practice: you can partially compensate for an imperfect generator with better prompting or fine-tuning, but you cannot compensate for a retriever that fundamentally misses relevant information. Conversely, retrieving relevant documents is necessary but not sufficient; the ranking and presentation of those documents materially influence generation quality. We must therefore evaluate retrieval along multiple dimensions: coverage of relevant information, ranking quality, and the positioning of necessary evidence within the limited context window provided to the generator.

The evaluation of retrieval also requires making decisions about what counts as "relevant." This is more fine-grained than it first appears. A document might contain the answer to a query, which makes it highly relevant. Another might give useful background context that helps the generator reason correctly, which makes it moderately relevant. A third might mention the topic without contributing anything useful. Binary relevance judgments, which classify each document as simply relevant or not, are easier to collect but obscure these important distinctions. Graded relevance judgments offer richer information at the cost of more complex annotation guidelines and higher annotator disagreement. We will cover metrics for both approaches.

Precision and Recall at K

The most intuitive metrics for retrieval quality are Precision@K and Recall@K. These measure the proportion of retrieved items that are relevant, and the proportion of all relevant items that were retrieved, considering only the top KK results. Before diving into formulas, notice what these two metrics capture at an intuitive level. Precision@K asks: "Of the documents I handed to the generator, what fraction were useful?" Recall@K asks: "Of all the useful documents in the knowledge base, what fraction did I manage to find?"

To state this formally, let RKR_K be the set of retrieved documents in the top KK positions, and RrelR_{rel} be the set of all relevant documents for a query in the entire corpus. Then:

Precision@K=∣RK∩Rrel∣∣RK∣\text{Precision@K} = \frac{|R_K \cap R_{rel}|}{|R_K|} Recall@K=∣RK∩Rrel∣∣Rrel∣\text{Recall@K} = \frac{|R_K \cap R_{rel}|}{|R_{rel}|}

where:

  • RKR_K: the set of documents retrieved in the top KK positions
  • RrelR_{rel}: the set of all relevant documents for the query across the full corpus
  • ∣S∣|S|: the cardinality (number of elements) of set SS
  • RK∩RrelR_K \cap R_{rel}: the intersection, meaning documents that were both retrieved and relevant

In RAG systems, KK is typically small, often between 3 and 10, constrained by the generator's context window length and the cost of processing long contexts. High precision ensures the generator receives mostly useful information, while high recall ensures necessary information is not missed. Neither alone is sufficient: a system that always retrieves exactly the one most relevant document has perfect precision but poor recall for complex queries; a system that retrieves every document in the knowledge base has perfect recall but precision near zero.

The key insight is that the context window constraint makes precision especially necessary in RAG, more so than in traditional web search. When you search the web, you can scroll through results and ignore irrelevant ones. When a language model processes a context window, every irrelevant chunk occupies space that could hold necessary evidence, and research suggests that the presence of distracting information can actively degrade generation quality by confusing the model.

These metrics offer complementary perspectives on retrieval effectiveness. Precision@K focuses on the signal-to-noise ratio within the context window. This keeps the generator is not distracted by irrelevant information that might lead to hallucinations or off-topic responses. Recall@K, conversely, measures completeness, showing whether the retrieval system successfully identified all relevant sources in the knowledge base. In practice, these metrics trade off against one another: increasing KK typically improves recall at the expense of precision, as including more documents dilutes the concentration of relevant information.

The Precision-Recall Tradeoff in RAG

Unlike web search where you can scroll through pages, RAG generators process a fixed context window. This makes Precision@K particularly important: irrelevant chunks consume useful tokens that could otherwise accommodate relevant information. However, Recall@K matters for queries requiring information dispersed across multiple documents. The optimal KK depends on the nature of the queries and the density of relevant information in the corpus. For factoid questions with single-document answers, small KK with high precision is ideal. For analytical questions requiring synthesis across sources, larger KK with better recall becomes necessary.

The constraint of limited context windows fundamentally changes how we interpret these metrics compared to traditional information retrieval. In web search, you might tolerate scanning through ten results to find one useful link. In RAG, every irrelevant document actively harms performance by occupying space that could hold necessary evidence. This makes high precision needed, particularly for the earliest positions in the ranking.

Out[3]:
Visualization
Line chart showing precision decreasing and recall increasing as K increases from 1 to 20, with a vertical dashed line at K=5.
Precision@K and Recall@K tradeoff as K increases from 1 to 20, simulated for a scenario with 10 relevant documents out of 100. Precision decreases as more documents are retrieved because later results tend to be less relevant, while recall increases and eventually plateaus when all relevant documents are found. The dashed vertical line at K=5 marks a typical RAG context window cutoff, showing that even at this moderate value, recall is still only partial.

Ranking Metrics: MRR and MAP

Precision and Recall at K treat the retrieved set as unordered, but ranking matters in RAG. Generators tend to focus more on information appearing earlier in the context, a phenomenon known as position bias or the "lost in the middle" effect. Think of the retrieved context as a stack of papers placed in front of the generator: it reads most carefully from the top and may skim or overlook material buried deep in the pile. Ranking metrics account for where relevant items appear, rewarding systems that place the most necessary information near the top.

The position of information within the retrieved context materially impacts generation quality. Research from Liu et al. (2023) demonstrated that language models often pay less attention to content in the middle of long contexts, focusing instead on the beginning and end of the provided documents. This U-shaped attention pattern means that a highly relevant document buried at position eight contributes less to answer quality than the same document at position two. Ranking metrics capture this positional sensitivity, rewarding systems that place the most relevant evidence where the generator will utilize it most effectively.

Understanding the "lost in the middle" effect has direct practical implications for RAG system design. Some practitioners deliberately reorder retrieved documents to place the highest-scored chunks at the very beginning and end of the context window, with less necessary supporting documents in the middle. This "placement strategy" exploits the known attention patterns of language models and can improve answer quality without any changes to the retrieval or generation components themselves. Evaluating systems with ranking-aware metrics ensures you are building this kind of positional awareness into your optimization process.

Out[4]:
Visualization
U-shaped attention curve across context positions 1 through 10, with a dip in performance in the middle positions annotated as 'Middle dip'.
The 'lost in the middle' effect in language model context processing, showing a U-shaped performance curve where information at the beginning and end of the context window is utilized more effectively than information in the middle. The dip centered around position 5-6 is the zone of reduced attention, where relevant documents are more likely to be overlooked by the generator even when present in the retrieved context.

Mean Reciprocal Rank (MRR) measures the position of the first relevant document. For a single query, the reciprocal rank is 1rank\frac{1}{\text{rank}} where rank is the position of the first relevant item. The reciprocal transformation is elegant: if the first relevant document is at position 1, the score is 1.0 (perfect). If it is at position 2, the score is 0.5. At position 4, 0.25. This creates a rapidly diminishing reward for finding relevant material later, which aligns with the generator's position bias described above.

MRR averages the reciprocal rank across all queries in the evaluation set:

MRR=1∣Q∣∑q=1∣Q∣1rankq\text{MRR} = \frac{1}{|Q|} \sum_{q=1}^{|Q|} \frac{1}{\text{rank}_q}

where:

  • ∣Q∣|Q|: the total number of queries in the evaluation set
  • rankq\text{rank}_q: the position (rank) of the first relevant document for query qq, starting from 1
  • 1rankq\frac{1}{\text{rank}_q}: the reciprocal rank for query qq, giving score 1.0 if rank is 1, 0.5 if rank is 2, and so on

If no relevant document appears in the retrieved results for query qq, the reciprocal rank is defined as 0. MRR is appropriate when a single relevant document suffices to answer the query, such as factoid questions with a definitive source. For example, "Who invented the telephone?" requires only finding one document containing the answer; once you have it, additional relevant documents add little value.

MRR gives an intuitive measure of how quickly you can find relevant information. A value of 1.0 indicates that the first retrieved document is always relevant, while a value of 0.5 suggests that the first relevant document typically appears at position 2. This metric is particularly useful for RAG applications involving simple factual lookups where a single authoritative source gives the complete answer. However, MRR has a basic limitation: it only considers the first relevant document. If a query requires synthesizing information from multiple sources, MRR is blind to the quality of later relevant documents.

Mean Average Precision (MAP) extends ranking evaluation to queries with multiple relevant documents. For each query, we calculate Average Precision (AP), which is the mean of precision values calculated at each rank position where a relevant document appears. Think of it this way: every time we encounter a relevant document while scanning down the ranked list, we record our current precision at that position. Then we average all those recorded precision values.

Formally, for a single query:

AP=∑k=1NPrecision@k×rel(k)∣Rrel∣\text{AP} = \frac{\sum_{k=1}^N \text{Precision@k} \times \text{rel}(k)}{|R_{rel}|}

where:

  • NN: the total number of documents retrieved for the query
  • Precision@k\text{Precision@k}: the precision at rank kk, calculated as ∣Rk∩Rrel∣∣Rk∣\frac{|R_k \cap R_{rel}|}{|R_k|}
  • rel(k)\text{rel}(k): a binary relevance indicator that equals 1 if the document at rank kk is relevant, and 0 otherwise
  • ∣Rrel∣|R_{rel}|: the total number of relevant documents for the query (the normalizing constant that makes AP comparable across queries with different numbers of relevant documents)

The rel(k)\text{rel}(k) indicator ensures we only accumulate precision at positions where a relevant document appears. This means that a run of irrelevant documents does not change the running sum, but when a relevant document finally appears at rank kk, we record Precision@k\text{Precision@k} at that moment. The intuition is that each relevant document "votes" for the quality of the ranking at the moment it was found.

MAP then averages AP across all queries in the evaluation set. This metric rewards systems that place multiple relevant documents near the top of the ranking, and it is sensitive to the order in which relevant documents appear. A system that retrieves three relevant documents at positions 1, 2, and 3 will score higher than one that retrieves the same documents at positions 1, 5, and 9, even though both might have identical Precision@10 scores. This sensitivity to ranking quality makes MAP particularly suitable for evaluating RAG systems designed to handle questions requiring synthesis from multiple sources.

MAP offers a more fine-grained view than MRR for complex queries requiring synthesis of multiple sources. Consider a query asking about the causes and effects of a historical event. A system that retrieves three relevant documents at positions 1, 2, and 3 will score higher than one that retrieves the same documents at positions 1, 5, and 9, even though both might have identical Precision@10 scores. This sensitivity to ranking quality makes MAP particularly suitable for evaluating questions with several relevant aspects.

Out[5]:
Visualization
Grouped bar chart comparing MRR, MAP, and NDCG@5 scores across four retrieval scenarios: Perfect, Good Early, Mixed, Poor Early.
Comparison of ranking metrics (MRR, MAP, NDCG@5) across four retrieval scenarios, ranging from perfect early ranking to poor early ranking where all relevant documents are buried. All three metrics decline as relevant documents are placed at lower ranks, but they differ in sensitivity: MRR drops most sharply when the first relevant document is delayed, while MAP and NDCG penalize poor placement of all relevant documents.

Graded Relevance: NDCG

Not all relevant documents are equally relevant. A chunk that directly answers the query is more useful than one that gives tangential background. A document containing a precise statistic is more useful than one that vaguely mentions the same topic. Binary relevance judgments force evaluators to collapse these real distinctions into a single bit, losing information that matters for system quality.

Binary relevance judgments simplify evaluation but obscure important distinctions in information quality. A document containing the exact answer to a query is fundamentally more useful than one that merely mentions related concepts. Think of relevance as a spectrum rather than a switch: at one end, a document that directly and completely answers the query; at the other end, a document that is completely off-topic; and in between, varying degrees of partial relevance, topical relevance, and contextual usefulness. Graded relevance acknowledges these differences, letting evaluators to distinguish between perfect matches, highly relevant documents, marginally relevant background material, and irrelevant content. This richer annotation lets metrics that better reflect the actual utility of retrieved documents.

Normalized Discounted Cumulative Gain (NDCG) handles graded relevance scores (e.g., 0 to 3) rather than binary judgments. The construction of NDCG proceeds in three steps, each building on the previous.

Step 1: Cumulative Gain (CG) at position KK simply sums the graded relevance scores of retrieved documents, ignoring their positions:

CG@K=∑i=1Kreli\text{CG@K} = \sum_{i=1}^K \text{rel}_i

where:

  • reli\text{rel}_i: the graded relevance score (e.g., 0 to 3) of the document at position ii
  • KK: the number of top documents considered in the ranking

CG has an obvious flaw: it assigns equal value to relevant documents regardless of where they appear. A system that returns the most relevant document at position 5 scores identically to one that returns it at position 1. Since position matters for RAG, we need to discount contributions from lower positions.

Step 2: Discounted Cumulative Gain (DCG) penalizes relevant items that appear lower in the ranking using a logarithmic discount factor:

DCG@K=∑i=1K2reli−1log⁡2(i+1)\text{DCG@K} = \sum_{i=1}^K \frac{2^{\text{rel}_i} - 1}{\log_2(i + 1)}

where:

  • reli\text{rel}_i: the graded relevance score of the document at rank ii
  • ii: the position of the document in the ranked list (starting from 1)
  • 2reli−12^{\text{rel}_i} - 1: the exponential gain function, giving exponentially more weight to higher relevance grades
  • log⁡2(i+1)\log_2(i + 1): the logarithmic discount factor that reduces the contribution of documents at lower ranks

The logarithm base ensures that each position contributes less than the previous, but the difference between positions 1 and 2 is larger than between positions 9 and 10. This shows the reality that early positions receive disproportionate attention. We use 2rel−12^{\text{rel}} - 1 to give exponentially more weight to highly relevant documents. With a 0-3 grading scale, the gains are 0, 1, 3, and 7 for grades 0, 1, 2, and 3 respectively. This means a grade-3 document contributes seven times as much gain as a grade-1 document, not just three times as much, which shows the intuition that a perfect answer is substantially more useful than a marginally useful one.

The DCG formula elegantly combines two important principles: the value of relevance and the cost of position. The exponential term in the numerator ensures that finding a highly relevant document (score 3) is substantially more useful than finding a moderately relevant one (score 2), specifically about 7/3≈2.37/3 \approx 2.3 times as useful based on gain values. The logarithmic denominator implements a smooth discounting of lower positions. This shows the diminishing attention that both human users and language models pay to later items in a list.

Step 3: Normalized DCG (NDCG) divides by the Ideal DCG (IDCG), which is the DCG of the perfect ranking where all relevant documents appear at the top in order of decreasing relevance:

NDCG@K=DCG@KIDCG@K\text{NDCG@K} = \frac{\text{DCG@K}}{\text{IDCG@K}}

where:

  • DCG@K\text{DCG@K}: the Discounted Cumulative Gain at position KK for the actual ranking
  • IDCG@K\text{IDCG@K}: the Ideal DCG at position KK, representing the maximum possible DCG if documents were ranked in perfect order of relevance

NDCG ranges from 0 to 1, where 1 is a perfect ranking. The reason is that the normalization by IDCG lets fair comparison across queries of varying difficulty. A query with many highly relevant documents in the corpus will have a high IDCG, while a query with only one relevant document will have a low IDCG. Without normalization, the former would dominate aggregate metrics regardless of retrieval quality. NDCG solves this by measuring the achieved fraction of the theoretically possible gain. This gives a standardized score that shows both the quality and ordering of retrieved documents.

In RAG evaluation, graded relevance is important because context windows are limited: placing a highly relevant chunk at position 8 when it should be at position 1 means it might get truncated or receive less attention from the generator. NDCG captures this cost precisely, which makes it the preferred metric when you have access to graded relevance judgments.

Out[6]:
Visualization
Bar chart with overlaid line plot showing the DCG discount factor 1/log2(i+1) for positions 1 through 10, with annotations at positions 1 and 10.
The logarithmic discount factor in DCG calculation, showing how the gain contribution of each position diminishes as rank increases. Position 1 has a discount factor of 1.00, meaning it contributes full gain, while position 10 has a factor of only 0.29, meaning the same relevance score contributes less than a third as much. This rapid decay shows the reality that users and language models pay decreasing attention to lower-ranked results.

Choosing Between Retrieval Metrics

With Precision@K, Recall@K, MRR, MAP, and NDCG available, the natural question is which to use when. The answer depends on your query types and evaluation goals. For simple factoid questions where a single relevant document suffices, MRR captures the most important information: how quickly does the system return a useful answer? For complex analytical questions requiring multiple sources, MAP or NDCG better reflect whether the system found and ranked all relevant evidence.

If your knowledge base contains documents with varying degrees of relevance (not just relevant or not), NDCG is superior because it uses the full relevance signal. If you only have binary relevance judgments, Precision@K, Recall@K, MRR, and MAP are your options. In practice, many production RAG evaluations report Precision@K and Recall@K alongside MRR or NDCG, giving a complete picture of both coverage and ranking quality.

One practical consideration is the cost of creating relevance judgments. Binary judgments (relevant or not) are faster and cheaper to annotate than graded judgments (0-3). For initial evaluation pipelines, binary judgments with Precision@K and MRR often give enough signal to guide development. Graded judgments and NDCG become more useful once you need to distinguish between systems that already reach decent binary precision and recall but differ in the quality of their ranked order.