Lesson 8 of 16 · Retrieval
Retrieval Techniques
Retrieve better RAG context: choose k and a minimum score, add metadata filters, use MMR to avoid near-duplicates and small-to-big retrieval for context.
- 6 min read
- Intermediate
- Reviewed
- Choose how many chunks to retrieve and when to drop weak ones
- Use metadata filters to retrieve from the right documents
- Avoid near-duplicate results with Maximal Marginal Relevance (MMR)
- Search small chunks but give the model their surrounding context
Beyond “top 5”
Plain retrieval takes the k most similar chunks. That's a fine start, but it can fail in predictable ways: it returns five copies of the same fact, pulls in old or irrelevant documents, or finds the right sentence without the context around it. Each technique in this lesson fixes one of these.
k and the minimum score
- k (how many chunks) trades recall against noise and cost. Typical values are 3 to 10 chunks in the prompt. Questions that need facts from several places need more.
- A minimum score drops chunks that are only weakly related, as in the first pipeline lesson.
A common pattern is to retrieve generously (say 20 to 50 candidates), then narrow down with filters, reranking or MMR to the few that go in the prompt.
Filters: search the right documents
Metadata filters, covered in the Vector Databases course, are one of the most effective retrieval improvements: search only the user's product, language, region, or documents they're allowed to see, or only the current version of a policy. A good filter removes whole categories of wrong answers that no amount of similarity tuning would catch.
Diversity with MMR
Knowledge bases contain near-duplicates: the same rule in the policy, the FAQ and an old intranet page. Plain top-k may fill every slot with the same fact.
import math
def cos(a, b):
return sum(x * y for x, y in zip(a, b)) / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
query = [1.0, 0.5, 0.4, 0.4] # "What are the rules for annual leave?"
candidates = {
"Leave policy: 25 days per year": [1.0, 0.90, 0.05, 0.00],
"Leave FAQ: you get 25 days a year": [1.0, 0.92, 0.00, 0.05],
"Old intranet page: 25 days of leave": [1.0, 0.88, 0.04, 0.02],
"Carry over up to 5 unused days": [1.0, 0.10, 0.90, 0.00],
"Book holiday two weeks ahead": [1.0, 0.10, 0.00, 0.90],
}
def top_k(k):
return sorted(candidates, key=lambda c: cos(query, candidates[c]), reverse=True)[:k]
def mmr(k, balance=0.5):
"""Maximal Marginal Relevance: relevant to the query, but not a repeat of what's already chosen."""
chosen = []
while len(chosen) < k:
def score(c):
relevance = cos(query, candidates[c])
redundancy = max((cos(candidates[c], candidates[s]) for s in chosen), default=0)
return balance * relevance - (1 - balance) * redundancy
best = max((c for c in candidates if c not in chosen), key=score)
chosen.append(best)
return chosen
print("Plain top 3:")
for c in top_k(3):
print(" ", c)
print("MMR top 3:")
for c in mmr(3):
print(" ", c)Plain top 3 spent all three slots on “25 days per year”. MMR kept the best of those, then chose the booking rule and the carry-over rule, so a question about leave “rules” gets all three facts. Raise balance towards 1 for more relevance, lower it for more variety.
Notice also that the old intranet page ranked first. Similarity can't tell an official page from an outdated copy. Metadata (a status: current filter, or a boost for official sources) can.
Small-to-big retrieval
Small chunks match questions precisely, but alone they may lack context. Large chunks give context, but match less precisely. Small-to-big retrieval gets both: search over small pieces, then hand the model the bigger piece they belong to.
import math, re
# ---- A tiny see-inside embedding model: one dimension per concept ----
CONCEPTS = {
"leave": "leave holiday holidays vacation annual time-off carried",
"sick": "sick ill illness unwell doctor self-certify",
"remote": "remote home hybrid office hours",
"expenses": "expenses expense claim reimbursed receipt receipts meals",
"equipment": "laptop laptops monitor headset equipment lost stolen",
"security": "password passwords 2fa two-factor login phishing security",
"parental": "parental maternity paternity baby birth adoption adoptive",
"training": "training course courses learning books conferences",
"travel": "travel trip trips flight flights train trains journeys",
"pay": "pay paid salary payroll",
}
WORDS = {c: set(words.split()) for c, words in CONCEPTS.items()}
def words(text):
return re.findall(r"[a-z0-9'-]+", text.lower())
def embed(text):
v = [sum(w in WORDS[c] for w in words(text)) for c in CONCEPTS]
length = math.sqrt(sum(x * x for x in v))
return [x / length for x in v] if length else v
def cosine(a, b):
return sum(x * y for x, y in zip(a, b)) # vectors are unit length
# ---- The knowledge base: sections of a company handbook ----
HANDBOOK = {
"Annual leave": "Full-time employees get 25 days of paid annual leave per year, plus public holidays. Book holiday in the HR portal at least two weeks ahead. Up to 5 unused days can be carried over to next year.",
"Sick leave": "If you are ill, tell your manager before 10am on your first day off. You can self-certify for up to 7 days; after that you need a note from a doctor. Sick pay is your full salary for up to 10 days per year.",
"Remote work": "You can work from home up to 3 days a week, with your manager's agreement. Core hours are 10am to 4pm. The office is open from 7am to 8pm.",
"Expenses": "Claim expenses within 30 days in the finance app, with a photo of each receipt. Meals on work trips are reimbursed up to 40 euros per day. Approved expenses are paid with your next salary.",
"Equipment": "New starters get a laptop, a monitor and a headset. Report a lost or stolen laptop to IT within 24 hours. Laptops are replaced every 4 years.",
"Security": "Use a password manager and turn on two-factor login (2FA) for every work account. Never share your password. Report phishing emails with the Report button in your mail app.",
"Parental leave": "Birth parents get 26 weeks of paid parental leave and partners get 4 weeks. Adoptive parents get the same leave as birth parents.",
"Training": "Every employee has a learning budget of 1,000 euros per year for courses, books and conferences. Courses over 300 euros need your manager's approval.",
"Business travel": "Book work trips in the travel portal. Fly economy for flights under 6 hours and premium economy for longer flights. Take the train for journeys under 4 hours.",
}
# Small chunks (single sentences) are precise to search...
sentences = []
for title, text in HANDBOOK.items():
for i, s in enumerate(text.split(". ")):
sentences.append({"section": title, "pos": i, "text": s.rstrip(".") + "."})
def search(question):
q = embed(question)
return max(sentences, key=lambda s: cosine(q, embed(s["section"] + ". " + s["text"])))
# ...but a single sentence often lacks context. Expand to its neighbours:
def with_neighbours(hit, window=1):
same = [s for s in sentences if s["section"] == hit["section"]]
return " ".join(s["text"] for s in same if abs(s["pos"] - hit["pos"]) <= window)
hit = search("What happens after 7 days off sick?")
print("Best sentence: ", hit["text"])
print("With neighbours:", with_neighbours(hit))Common mistakes
Expand a search hit to include its neighbouring chunks, so the LLM sees the surrounding context.
chunks = [
"Laptops are replaced every 4 years.",
"Report a lost laptop within 24 hours.",
"Use a password manager.",
"Turn on two-factor login.",
"Never share your password.",
]
hit = 4 # the search matched the last chunk
window = 1 # include this many chunks on each side
# Print the hit together with its neighbours, in order, one per line.
# Be careful not to go past either end of the list.
print(chunks[hit])
Your top 5 results are all near-identical copies of the same paragraph from different pages. Which technique helps most?
Summary
- Retrieve generously, then narrow down: k, a minimum score, filters, reranking or MMR.
- Filters remove whole categories of wrong answers (product, language, version, access).
- MMR balances relevance and diversity, avoiding near-duplicates.
- Small-to-big retrieval searches small chunks but returns their neighbours or parent section.
Next: combining keyword and semantic search in a RAG system, and measuring which works best.
Finished reading? Tick it off to track your progress.