PREP WITH PROOF
Menu
AI & RETRIEVAL / PRACTICAL GUIDE

RAG Retrieval Metrics: Recall@k, MRR, and nDCG

Compare RAG retrieval coverage and ranking with Recall@k, Precision@k, MRR, and nDCG. Includes tested Python, label conventions, and a worked example.

THE QUICK ANSWER

Use Recall@k for coverage, Precision@k for the fixed result budget, MRR@k for the first relevant hit, and nDCG@k for graded ranking quality. Define the label unit and metric conventions first. Evaluate retrieval separately from answer grounding and compare the same query set and corpus version.

Pick the retrieval question before picking a score

A retrieval change can find more relevant passages while placing the best one later. Another change can place one useful passage first while missing the rest of the evidence. Calling either result “better RAG” hides the decision you actually need to make. Measure coverage and ordering separately before evaluating the generated answer.

This guide focuses on ranked retrieval metrics, using labeled passage IDs and a small deterministic example. It complements passage inspection and citation audits rather than replacing them. A perfect ranking score does not show that a model followed the evidence, respected document access, or answered the user correctly.

Start by defining the retrieval output your application consumes: the initial search results, the reranked list, or the final passages actually included in the prompt. Those are different checkpoints. If a token budget removes a relevant passage after reranking, a score taken before that removal overstates the evidence available to generation.

Source: ir-measures: retrieval measure definitions and parameters ↗

Define relevance at a stable unit

Choose document IDs, passage IDs, or evidence units and keep that unit consistent. A document-level label is too coarse when only one paragraph answers the question. Conversely, several overlapping chunks of the same paragraph should not automatically count as several independent pieces of evidence.

For each query, record the relevant IDs and any graded labels, along with the corpus version. In this example, grade 0 means irrelevant, 1 useful supporting context, 2 directly useful evidence, and 3 especially useful evidence. This is an illustrative rubric, not an industry-wide standard; the definition belongs with the scores.

Keep unjudged results distinguishable from judged irrelevant results. A missing label might mean an annotator never saw the passage. The code below rejects unknown IDs instead of silently treating them as irrelevant. That forces a label review when a new retriever surfaces something outside the judged pool.

Source: Ragas: ID-based and reference-context recall ↗

Recall, precision, reciprocal rank, and nDCG answer different questions

At cutoff k, Recall@k is the fraction of labeled relevant items retrieved in the first k positions. Precision@k is the number of relevant items in those positions divided by k. Here an unfilled result slot counts against precision. State that convention if a service sometimes returns fewer than k items.

Reciprocal rank at k is 1 divided by the position of the first relevant result within the cutoff, or zero when there is none. MRR@k is the mean of those per-query reciprocal ranks. It rewards finding an early relevant result but does not distinguish retrieving one relevant passage from retrieving several after that first hit.

nDCG@k evaluates graded relevance and position relative to an ideal ranking for the same query. This guide uses gain = 2^grade − 1 and discount = log2(rank + 1), with ranks starting at 1. Divide the discounted gain of the actual top k by the discounted gain of the ideal top k. Libraries differ in gain conventions and tie handling; record both before comparing numbers.

MetricUseful when you needWhat can remain hidden
Recall@kCoverage of labeled relevant evidenceWhether the best evidence appears early
Precision@kRelevant evidence within a fixed result budgetRelevant evidence that was never retrieved
MRR@kAn early first relevant hitQuality and completeness after the first hit
nDCG@kGraded relevance placed near the topWhether labels reflect the real task

Source: ir-measures: retrieval measure definitions and parameters ↗

One toy query, three sharply different rankings

Imagine a synthetic query with three relevant passages: a has grade 3, b grade 2, and c grade 1. Passages x, y, and z are judged irrelevant. The labels are invented learning data. They are not measurements from a production assistant or a benchmark dataset.

Ranking A returns x, a, b. Ranking B returns c, x, y. At k = 3, A has higher recall but B has the better first-hit position. Under the stated graded rubric, A has much higher nDCG because it includes the high-value evidence, even though an irrelevant passage occupies its first slot.

Ranking C returns a, b, c and is ideal for this label set at k = 3. It reaches 1.0 on all four per-query measures. That means it matches this rubric, not that it guarantees a complete answer: a query needing a combination of facts can require a richer evidence annotation than a list of individually relevant passages.

Top 3 rankingRecall@3Precision@3RR@3nDCG@3 (rounded)
A: x, a, b0.6670.6670.5000.630
B: c, x, y0.3330.3331.0000.106
C: a, b, c1.0001.0001.0001.000

Compute the stated conventions with plain Python

Save this as retrieval_metrics.py and run it with Python 3.12 or later. It uses the standard library, makes no network calls, and does not invoke an embedding or language model. The input list is already ordered; the function does not sort by similarity or decide whether a passage is relevant.

The function rejects duplicate ranked IDs, unknown IDs, invalid grades, and nonpositive cutoffs. It also rejects a query with no labeled relevant item because its recall and normalized ideal gain are undefined under this contract. Evaluate no-answer queries separately rather than quietly deleting them from the dataset or awarding an arbitrary perfect score.

The returned rr value describes one query. Average it over the explicitly eligible query set to report MRR. Empty retrieved results are allowed and score zero for an otherwise answerable labeled query. Short lists keep the fixed k precision denominator; ideal gain still considers all relevant labeled items.

import math


def score_ranking(ranked: list[str], grades: dict[str, int], k: int):
    if type(k) is not int or k <= 0:
        raise ValueError("k must be a positive integer")
    if any(not isinstance(doc, str) or not doc for doc in grades):
        raise ValueError("judgment IDs must be nonempty strings")
    if any(type(g) is not int or not 0 <= g <= 3 for g in grades.values()):
        raise ValueError("grades must be integers from 0 to 3")
    if len(ranked) != len(set(ranked)):
        raise ValueError("duplicate ranked IDs")
    if any(doc not in grades for doc in ranked):
        raise ValueError("unjudged ranked ID")
    relevant = {doc for doc, grade in grades.items() if grade > 0}
    if not relevant:
        raise ValueError("no labeled relevant item; score separately")
    top = ranked[:k]
    hits = sum(doc in relevant for doc in top)
    rr = next((1 / rank for rank, doc in enumerate(top, 1)
               if doc in relevant), 0.0)

    def dcg(values):
        return sum((2 ** grade - 1) / math.log2(rank + 1)
                   for rank, grade in enumerate(values, 1))

    ideal = sorted(grades.values(), reverse=True)[:k]
    return {"recall": hits / len(relevant), "precision": hits / k,
            "rr": rr, "ndcg": dcg([grades[doc] for doc in top]) / dcg(ideal)}


grades = {"a": 3, "b": 2, "c": 1, "x": 0, "y": 0, "z": 0}
for name, ranking in {"A": ["x", "a", "b"],
                      "B": ["c", "x", "y"],
                      "C": ["a", "b", "c"]}.items():
    result = score_ranking(ranking, grades, 3)
    print(name, {metric: round(value, 3) for metric, value in result.items()})

Make an independent implementation agree before trusting a dashboard

We executed the example with CPython 3.12.14 and checked its displayed values. For full rankings of the six judged IDs, we also compared the nDCG calculation against scikit-learn across all 720 permutations and cutoffs 1 through 6. The comparison supplies transformed gains, 2^grade − 1, as scikit-learn’s relevance values so its gain convention matches this example.

That is an arithmetic cross-check, not an evaluation of a RAG product. Ties are absent because each permutation has an explicit order. A real retriever may return tied scores; choose a stable ordering rule or use a metric implementation that handles ties according to the evaluation contract.

If two tools disagree, first compare their relevance threshold, gain function, cutoff, duplicate handling, empty-query policy, and treatment of unjudged results. A difference at that level can explain the score before any retrieval model changes. Keep an explicit small fixture alongside the production evaluation pipeline.

Source: scikit-learn: nDCG scoring, relevance inputs and ties ↗

Compare the same queries, then inspect the cases behind the mean

Use a fixed evaluation query set when comparing two retrieval configurations. Keep corpus version, query filters, passage identity, and cutoff aligned. If chunking changes, establish how the old evidence labels map to the new chunks before calculating a delta; otherwise the denominator changes beneath the experiment.

Report the number of queries scored and the number excluded, with reasons. Macro-average recall gives each eligible query equal weight, while aggregating hits and relevant counts across queries weights queries with more relevant items more heavily. Choose deliberately and label the aggregation so reviewers can reproduce it.

Break results into meaningful slices such as short fact lookups, multi-evidence questions, recent documents, and queries requiring access filters. An improved mean can coexist with severe regressions on a small slice. For a close decision, inspect paired per-query changes and uncertainty rather than declaring victory from a tiny score difference.

Do not average rankings A, B, and C from the worked example and call the result MRR for a system. They are three alternative configurations for one query. A system-level comparison requires one result per eligible query for each configuration, followed by the chosen aggregation. Keep configuration identity in the result record so different runs cannot be mixed accidentally.

Freeze the evaluation split before tuning. Repeatedly selecting settings against the same small set can fit its particular wording and labels. Keep a separate held-out set for the final comparison and refresh evaluation coverage when the corpus or real query population changes. Preserve older cases when they still represent supported tasks.

Source: Ragas: ID-based and reference-context recall ↗

Use score disagreements to choose the next retrieval experiment

Low recall at the allowed cutoff suggests investigating whether the right evidence is indexed, eligible under filters, and retrievable for the query. Inspect misses before expanding k: a stale corpus or wrong access filter is not repaired by returning more unrelated passages.

High recall with a weak first hit or low nDCG points toward ordering and relevance quality. Compare the ranked passages and consider a controlled reranking or hybrid-search experiment. Preserve the same candidate and label contract while testing the change, and measure its latency and resource cost separately.

Raising k often increases recall but can increase prompt size and dilute useful context. Evaluate the final packed context as well as the search list. Measure what generation actually receives, especially when deduplication, truncation, or document expansion changes the set after retrieval.

Source: ir-measures: retrieval measure definitions and parameters ↗

Keep answer grounding and access control as separate checks

A labeled relevant passage can be retrieved and then ignored. A generated claim can be supported by a retrieved passage but still answer the wrong question. Retrieval relevance, answer support, task correctness, and access enforcement need their own checks; one retrieval score cannot stand in for all of them.

The existing grounded-answer and citation-audit guides cover claim-to-source review. Use those after the retrieval experiment, preserving the exact passages passed to generation. Judge whether citations support the claims and whether the answer adds unsupported quantities, dates, or conditions.

Finish the comparison with a compact experiment record: query set and corpus version, label unit and rubric, metric conventions, per-query results, runtime cost, and representative regressions. A useful retrieval metric explains a tradeoff you can inspect. It does not turn a synthetic fixture into evidence of production quality.

Source: Ragas: ID-based and reference-context recall ↗

KEEP THESE THREE THINGS

Your next steps

  1. Write down passage identity, relevance rubric, cutoff, and treatment of incomplete judgments.
  2. Check metric arithmetic on a small fixture before comparing retrieval configurations.
  3. Inspect per-query regressions and the final packed context, then evaluate the answer separately.

Sources & official resources

Linked resources checked on 2026-10-24. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →