Sub topic 15
Measuring and tuning relevance
This chapter assumes you know how an inverted index and BM25 scoring work, and that you can read a basic Elasticsearch-style query. By the end you should be able to set up a repeatable way to measure search quality and use it to change ranking safely.
Why "it looks good" is not enough
Relevance is how well the ordered results match what the user wanted. Without measurement, tuning is guesswork. You fix one query, break three others, and never find out. Search also changes over time: new products, new synonyms, new analyzers, and engine upgrades all shift the ranking.
Treat relevance like latency or error rate. Define a metric, record a baseline, change one thing, and compare.
The evaluation loop
Building a judgment set
A judgment set is a list of queries, each with documents labeled by how relevant they are. It is the ground truth for offline evaluation.
- Sample queries from logs. Include the most frequent queries (the head) and a random slice of rare ones (the tail). Head queries matter for volume. Tail queries expose analyzer and synonym gaps.
- Pick documents to judge. Take the top 10 to 20 results from the current system, plus results from candidate variants. Judging only your current top results hides documents the system fails to surface.
- Assign graded labels. A common scale is 0 (irrelevant), 1 (related), 2 (good), 3 (perfect). Graded labels let metrics reward putting the best result first.
- Write labeling guidelines. For the query "apple", state whether the fruit, the company, or both count as relevant. Two labelers should agree most of the time. If they do not, the guideline is ambiguous.
A set of 50 to 200 queries is enough to start. Keep it versioned next to your code.
Metrics
| Metric | What it measures | Use it when |
|---|---|---|
| Precision@k | Fraction of the top k results that are relevant | Users scan a short list |
| Recall@k | Fraction of all relevant documents found in the top k | Missing a result is costly, as in legal or support search |
| MRR (mean reciprocal rank) | Average of 1 / rank of the first relevant result | One right answer is expected, as in navigational queries |
| NDCG@k | Graded gain, discounted by rank, normalized to the ideal ordering | Several results matter and relevance has degrees |
| Zero-result rate | Share of queries returning nothing | Monitoring in production, no labels needed |
NDCG (normalized discounted cumulative gain) is the usual headline metric. Each result contributes a gain based on its grade, divided by a log of its position. The sum is divided by the best possible sum for that query, so scores fall between 0 and 1 and can be averaged across queries.
Computing metrics in code
import math
def dcg(grades):
return sum((2 ** g - 1) / math.log2(i + 2) for i, g in enumerate(grades))
def ndcg_at_k(ranked_ids, judgments, k=10):
gains = [judgments.get(d, 0) for d in ranked_ids[:k]]
ideal = sorted(judgments.values(), reverse=True)[:k]
best = dcg(ideal)
return dcg(gains) / best if best > 0 else 0.0
def reciprocal_rank(ranked_ids, judgments, threshold=1):
for rank, doc_id in enumerate(ranked_ids, start=1):
if judgments.get(doc_id, 0) >= threshold:
return 1.0 / rank
return 0.0
def precision_at_k(ranked_ids, judgments, k=5, threshold=1):
top = ranked_ids[:k]
hits = sum(1 for d in top if judgments.get(d, 0) >= threshold)
return hits / k
judgments = {"p1": 3, "p2": 2, "p3": 0, "p4": 1}
ranking_a = ["p3", "p1", "p2", "p4"]
ranking_b = ["p1", "p2", "p4", "p3"]
for name, ranking in [("A", ranking_a), ("B", ranking_b)]:
print(
name,
round(ndcg_at_k(ranking, judgments, k=4), 2),
round(reciprocal_rank(ranking, judgments), 2),
precision_at_k(ranking, judgments, k=4),
)
# A 0.68 0.5 0.75
# B 1.0 1.0 0.75Both rankings have the same precision@4, because both contain the same three relevant documents. Only NDCG and MRR notice that A puts an irrelevant document first. Choosing a metric that sees your problem matters as much as the score itself.
Documents with no judgment are scored as 0 here. This is a known weakness: a good document nobody labeled counts as bad. Re-judge the new top results whenever a variant surfaces unlabeled documents.
Tuning levers
Change the cheapest and most predictable things first.
- Analysis. Wrong stemming, missing synonyms, or stripped punctuation (such as "c++") cause misses that no scoring change fixes. Check the zero-result queries first.
- Field boosts. A match in the title should usually outrank a match in the description. Boost multiplies a field's score.
- Scoring parameters. BM25 has
k1(how fast term frequency saturates) andb(how strongly length is normalized). The defaults, 1.2 and 0.75, are reasonable. For short fields such as titles, a lowerboften helps, since length differences there carry little signal. - Business signals. Popularity, recency, margin, or stock status can be blended into the score. Keep these weights small so they reorder close matches instead of overriding text relevance.
- Query structure. Combine exact-phrase matches, prefix matches, and fuzzy matches with different weights so the strictest match ranks highest.
A boosted multi-field query with a popularity signal looks like this:
{
"query": {
"function_score": {
"query": {
"multi_match": {
"query": "running shoes",
"fields": ["name^3", "description"],
"type": "best_fields"
}
},
"field_value_factor": {
"field": "sales_rank_score",
"modifier": "log1p",
"factor": 0.2,
"missing": 0
},
"boost_mode": "sum"
}
}
}Here name^3 triples the weight of title matches. The log1p modifier compresses the popularity value, so a bestseller with 100,000 sales does not drown out a better text match. Adding the signal with sum keeps it a bounded nudge.
Change one thing at a time
Run the full judgment set after each change and compare per-query results, not just the average. A rise in mean NDCG can hide a handful of queries that got much worse. Keep a list of must-not-break queries, such as brand names and top sellers, and fail the check if any drop.
Online measurement
Offline metrics tell you whether a change is plausible. Online tests tell you whether users benefit.
- A/B test the old and new ranking on a share of traffic. Compare click-through rate, conversion, reformulation rate (users immediately searching again), and zero-result rate.
- Interleaving mixes results from both rankings in one list and counts which side's results get clicked. It needs less traffic than a split test.
- Click logs as labels. Clicks are cheap but biased. Users click higher positions more, regardless of quality (position bias). A result nobody saw has no clicks. Use clicks to find problem queries and to supplement labels, not as the only truth.
Log the query, the returned document IDs with positions, and the clicked IDs. Without this data you cannot do either evaluation later.
Common errors
- Averaging hides regressions. Report the number of queries that improved, stayed equal, and worsened, alongside the mean.
- Tuning on head queries only. Most unique queries are rare, and they often fail first.
- Mixing index changes with query changes. If you reindex with a new analyzer and change boosts in the same step, you cannot tell which helped.
- Ignoring small shards. BM25 uses document frequency statistics per shard. On a small test index with several shards, scores can differ from production, so offline results may not transfer. Evaluate against production-like data.
- Unstable judgments. Product catalogs change. Re-check labels when documents are removed or renamed.
Operationalizing it
Put the judgment set in version control and run the evaluation in CI against a test index built from a data snapshot. Fail the build if mean NDCG drops by more than a set margin or if a must-not-break query regresses. In production, dashboard the zero-result rate, click-through rate on the first page, and reformulation rate, and alert on sudden shifts, which often signal a broken sync or analyzer change.
Exercise
Two ranking variants have identical precision@5 on your judgment set, but variant B has a much higher NDCG@5. What does this tell you, and which online metric would you check first to see if users notice?
Show answer
Both variants return the same number of relevant documents in the top 5, but B places the highly relevant ones higher. Precision ignores order and grade, while NDCG rewards putting the best results first. To see whether users notice, check click-through rate on the top positions, or the reformulation rate, in an A/B test or interleaving experiment.
Exercise
You raised the boost on the title field and mean NDCG rose from 0.71 to 0.73. Why should you still look at per-query results before shipping?
Show answer
The mean can hide regressions. A few queries, such as brand name or exact-product searches, may have dropped sharply while many others rose slightly. Compare per query, count improved and worsened queries, and check your must-not-break list before shipping.