Calculate Ranking Metrics for Search Results
Compute precision at three and reciprocal rank for two retrieval runs, then compare what each metric rewards.
Difficulty Intermediate
Set up a query and judgements
Use Python 3 and a fictional catalogue. For the query “replace a bicycle tyre”, mark documents B and D relevant before looking at ranked results. Assume unmarked documents in this small fixture are known irrelevant.
Compute two measures
relevant = {"B", "D"}
runs = {"A": ["A", "B", "D", "C"], "B": ["D", "C", "A", "B"]}
for name, hits in runs.items():
assert len(hits) == len(set(hits))
first = next((i for i, item in enumerate(hits, 1)
if item in relevant), None)
precision_at_3 = sum(item in relevant for item in hits[:3]) / 3
reciprocal_rank = 1 / first if first else 0
print(name, round(precision_at_3, 2), reciprocal_rank)
Run A retrieves two relevant documents in the top three. Run B retrieves one there but the first result is already relevant. Precision at three measures the quality of a fixed window. Reciprocal rank captures the position of the first relevant result.
Check and extend
Add a query with no relevant documents in its returned results and observe a reciprocal rank of zero. Average per-query reciprocal ranks to obtain mean reciprocal rank. Agree on how to handle queries with incomplete judgements and result lists shorter than three before comparing real systems. Keep duplicate document IDs out of evaluation runs.
Troubleshooting and practice
If duplicate copies inflate your apparent result quality, deduplicate using a consistent document identity before scoring. If judges disagree, keep both recorded judgements and investigate the ambiguity. Try swapping the first two entries in run A and explain which metric changes. Use public or fictional queries in shared reports to avoid exposing search histories.