Retrieval Quality and Reranking

Updated · 6 min read
hardPython 3.13airagretrievalrerankingevaluation

Retrieval quality is how often search returns the passage that actually answers the question. It is measured with a test set: real questions, each paired with the passage a person marked as the right answer. Techniques such as hybrid search, reranking and metadata filters can improve it, but only measurement tells you whether they do on your data.

Ways to Improve Retrieval

TechniqueDescription
Hybrid searchIt is used to combine keyword and semantic scores, helping with exact names and codes
RerankingIt is used to re-score the top candidates with a slower, more careful model that reads question and passage together
Metadata filtersIt is used to search only the right documents, such as the current year or one category
Better chunksIt is used to make each passage a complete idea (see "Chunking Documents")

Measuring Retrieval

Measure every technique on your own questions
MeasureDescription
Hit rate at kIt is used to count how often the right passage is in the top k results
Ranked firstIt is used to count how often the right passage is the very first result
Test setReal questions paired with the right passage, marked by a person

Example: Comparing Four Methods

This program reuses the 50 FAQ answers (faq.json) from "Semantic Search" and needs one more small model, a reranker, which downloads on first use:

Python
import json
import re
 
from sentence_transformers import CrossEncoder, SentenceTransformer
 
faq = json.load(open("faq.json"))
texts = [item["text"] for item in faq]
TESTS = {  # question: the FAQ id a person marked as the right answer
    "How much do chemistry experiments cost?": 1,
    "We can't afford the fees this year. Is there any help?": 8,
    "Do brothers and sisters pay less?": 9,
    "What happens if I pay late?": 7,
    "When are applications due?": 14,
    "Is there an entrance exam for grade 11?": 20,
    "When do the holidays start in December?": 32,
    "What time does the first class begin?": 28,
    "When are final exams?": 30,
    "My kid is sick today, what should I do?": 43,
    "Where can my son get help with homework?": 44,
    "Can I ride my bicycle to school?": 46,
}
 
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
answer_vectors = model.encode(texts, normalize_embeddings=True)
 
def words(text):
    return set(re.findall(r"[a-z]+", text.lower()))
 
def keyword_scores(q):
    return [len(words(q) & words(t)) / len(words(q)) for t in texts]
 
def semantic_scores(q):
    return list(answer_vectors @ model.encode(q, normalize_embeddings=True))
 
def hybrid_scores(q):
    return [0.3 * k + 0.7 * s for k, s in zip(keyword_scores(q), semantic_scores(q))]
 
def top(scores, k=3):
    return sorted(range(len(texts)), key=lambda i: -scores[i])[:k]
 
def reranked(q, k=3):
    candidates = top(semantic_scores(q), k=10)  # retrieve 10, then rerank them
    scores = reranker.predict([(q, texts[i]) for i in candidates])
    return [candidates[i] for i in scores.argsort()[::-1][:k]]
 
methods = {"keyword": lambda q: top(keyword_scores(q)), "semantic": lambda q: top(semantic_scores(q)),
           "hybrid": lambda q: top(hybrid_scores(q)), "semantic + rerank": reranked}
for name, search in methods.items():
    hits = sum(TESTS[q] - 1 in search(q) for q in TESTS)
    first = sum(search(q)[0] == TESTS[q] - 1 for q in TESTS)
    print(f"{name:18} right answer in top 3: {hits}/{len(TESTS)} | ranked first: {first}/{len(TESTS)}")
Output
keyword            right answer in top 3: 4/12 | ranked first: 3/12
semantic           right answer in top 3: 12/12 | ranked first: 11/12
hybrid             right answer in top 3: 12/12 | ranked first: 9/12
semantic + rerank  right answer in top 3: 11/12 | ranked first: 10/12

Explanation: TESTS holds 12 questions with the FAQ answer a person marked as right. Each method is scored by how often that answer lands in the top 3, and how often it's first. Hybrid mixes 30% keyword and 70% semantic scores. The reranker reads each question with each of the top 10 semantic results and re-orders them. On these questions, plain semantic search did best. Hybrid's misses came from shared words: "fees" pulled the online-payment answer above the waiver answer. The reranker, trained on web search queries, ranked the waiver answer third and pushed the attendance answer for the sick-child question out of the top 3.

Growing the Test Set

A test set is only as good as the questions in it.

Common Mistakes

Adding techniques because they're popular. Measure each one on your test set.

Testing only with questions you wrote. Real users phrase things differently; collect their questions.

Measuring once. Rerun the test after every change to documents, chunking or models.

Interview Corner

How do you measure retrieval quality?

With a test set of real questions paired with the correct passages, counting how often the right passage appears in the top k (hit rate) and how often it ranks first.

What is reranking?

A second step that re-scores the top candidates with a more careful model that reads the question and each passage together. It often improves ordering, but it adds time and should be measured on your data.

Practice

Exercise: break the tie. Add four questions that use exact terms, such as "What is the $10 charge?" and "Room 104?". Rerun the comparison. Does keyword or hybrid search improve on these?

Check your understanding:

  1. What does "hit rate at 3" mean?
  2. Which method did best on this test set?
  3. Why might hybrid search do better on other data?

Quick check: retrieval quality

4 questions
1What is a retrieval test set?
2How often did keyword search put the right answer in the top 3?
3What does a reranker do?
4What is the main lesson of the comparison?

Key Takeaways

Quick reference

TechniqueUse when
Hybrid searchExact names, codes and numbers matter
RerankingThe right passage is retrieved but ranked too low
Metadata filtersOnly some documents should be searched

Was this tutorial helpful?

Lesson 98 of 186