Sub topic 9
Retrieving the top-k passages
This chapter covers the retrieval step of a RAG pipeline: given a query, return the k most relevant stored passages. It assumes you can read basic Python, know what an embedding vector is, and understand the dot product. Chunking, embedding, and similarity metrics are covered in earlier chapters, so here they are treated as inputs.
What retrieval does
Retrieval takes a user question and returns a short, ranked list of passages from your index. The language model never sees the whole corpus. It sees only what retrieval hands over, so retrieval sets the ceiling on answer quality. If the right passage is not in the top k, the model cannot use it.
The steps are:
- Embed the query with the same model that embedded the chunks.
- Score the query vector against stored vectors.
- Optionally discard candidates that fail a metadata filter.
- Sort by score and keep the k best.
- Pass those passages to prompt assembly.
Exact top-k with brute force
The simplest retriever scores every stored vector and sorts. It is exact: no relevant vector is missed because of the search method. It is a good baseline and works well up to tens of thousands of chunks.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return dot / (na * nb) if na and nb else 0.0
def top_k(query_vec, index, k=3):
# index is a list of (text, vector) pairs
scored = [(cosine(query_vec, vec), text) for text, vec in index]
scored.sort(key=lambda pair: pair[0], reverse=True)
return scored[:k]The cost grows linearly with the number of chunks, and each comparison costs time proportional to the vector dimension. Approximate indexes, covered in the previous chapter, reduce that cost by examining only part of the data. Everything below applies whether the search is exact or approximate.
Choosing k
The value of k controls a trade-off between coverage and noise.
| Choice | Benefit | Cost |
|---|---|---|
| Small k (1 to 3) | Short prompt, low cost, little distraction | Misses answers that span chunks or rank 4th |
| Medium k (4 to 8) | Good coverage for most question types | More tokens, some irrelevant text |
| Large k (20 or more) | High chance the answer is present | Long prompt, diluted attention, higher cost |
A common pattern is to retrieve a larger candidate set (say 20 to 50) and then shrink it with reranking before prompting. Without a reranker, choose k by measuring recall at k on a labeled set of questions, as described in the evaluation chapter. Pick the smallest k where recall stops improving much.
Also consider the token budget. If each chunk is about 500 tokens and k is 8, retrieval alone consumes 4,000 tokens before the question and instructions.
Metadata filtering
Each chunk should be stored with metadata: source document, section, date, language, product version, and who may read it. A filter restricts the candidates to chunks whose metadata match a condition, such as version == "3.2".
Filters matter for three reasons:
- Relevance. A question about version 3.2 should not return text about version 1.0, even if the wording is similar.
- Access control. Users should only retrieve documents they are allowed to see.
- Efficiency. A filter can shrink the search space.
Here is a filter applied to the brute-force retriever. Each record carries a metadata dictionary.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return dot / (na * nb) if na and nb else 0.0
def top_k_filtered(query_vec, records, k=3, where=None):
# records: list of dicts with "text", "vector", "meta"
where = where or {}
candidates = [
r for r in records
if all(r["meta"].get(key) == value for key, value in where.items())
]
scored = [(cosine(query_vec, r["vector"]), r["text"]) for r in candidates]
scored.sort(key=lambda pair: pair[0], reverse=True)
return scored[:k]
records = [
{"text": "Reset the device with the side button.", "vector": [1.0, 0.0], "meta": {"version": "3.2"}},
{"text": "Hold the front switch to reset.", "vector": [0.9, 0.1], "meta": {"version": "1.0"}},
{"text": "Charge for two hours before first use.", "vector": [0.0, 1.0], "meta": {"version": "3.2"}},
]
print(top_k_filtered([1.0, 0.0], records, k=2, where={"version": "3.2"}))The version 1.0 record is the second closest vector, but the filter removes it, so the result holds only version 3.2 text.
Pre-filtering and post-filtering
There are two places to apply a filter, and they behave differently in approximate indexes.
- Pre-filtering restricts the search to matching chunks before ranking. The result always has up to k matching items.
- Post-filtering takes the top k from the whole index, then removes non-matching items. If most of the top k fail the filter, you get fewer than k results, possibly none.
A simple workaround for post-filtering is to over-fetch, for example retrieving 5 times k and then filtering. Check how your vector store implements filtering, because some approximate indexes lose recall when a filter is very selective.
For access control, never rely on the model to hide restricted text. Filter before the passages reach the prompt.
Score thresholds
Top-k always returns k items, even when nothing is relevant. A question outside your corpus still gets the three "closest" chunks, and the model may build an answer from them. A minimum score threshold lets retrieval return fewer passages, or none.
def apply_threshold(results, min_score=0.3):
# results: list of (score, text), best first
return [(s, t) for s, t in results if s >= min_score]Score scales differ between embedding models, so a threshold of 0.3 means different things in different systems. Choose it empirically: look at the scores of known relevant and known irrelevant chunks and pick a value that separates them. If the filtered list is empty, the prompt should tell the model there is no context, so it can say it does not know.
Reducing redundancy
Overlapping chunks and duplicated documents often produce near-identical results. Five copies of the same paragraph waste the budget. Two common fixes:
- Deduplicate at ingestion by hashing normalized text.
- Use maximal marginal relevance (MMR), which picks each next result by balancing similarity to the query against similarity to results already chosen.
Common errors
- Mismatched embedding models. Query and chunks must use the same model and the same settings. Mixing them produces meaningless scores.
- Unnormalized vectors with a dot product. If the index uses a dot product, vectors should be normalized, or longer vectors will win regardless of meaning.
- Fixed k for every query. A broad question may need more passages than a lookup question.
- Ignoring ties and ordering. Equal scores can come back in arbitrary order. Sort with a stable tie-breaker, such as document id, when you need repeatable results.
- Judging only by the final answer. Check retrieval separately. A wrong answer may come from a missed passage or from a bad generation, and the fix differs.
Measuring retrieval
To tune k, filters, and thresholds, measure recall at k: the fraction of known relevant documents that appear in the top k.
def recall_at_k(retrieved_ids, relevant_ids, k):
relevant = set(relevant_ids)
if not relevant:
return 0.0
hits = set(retrieved_ids[:k]) & relevant
return len(hits) / len(relevant)
print(recall_at_k(["d4", "d1", "d9", "d2"], ["d1", "d2"], k=3))
print(recall_at_k(["d4", "d1", "d9", "d2"], ["d1", "d2"], k=4))The first call prints 0.5 because only d1 is in the top 3. The second prints 1.0.
Exercise
A user asks about version 3.2 of a product. Your approximate index returns its top 5 results, and then your code removes chunks not tagged version 3.2. Often only one or two chunks remain. What is happening, and name two ways to fix it?
Show answer
This is post-filtering. The top 5 are chosen from the whole index, so most of them belong to other versions and get removed afterward. Fixes: use pre-filtering so the index only ranks version 3.2 chunks, or over-fetch (for example retrieve 25 and filter down to 5). Raising k alone before the filter also helps, but pre-filtering is the more reliable choice.
Exercise
Why should a RAG system use a minimum score threshold in addition to top-k, and why can't you copy a threshold from another system?
Show answer
Top-k always returns k items, even for questions the corpus cannot answer, which invites the model to build answers from irrelevant text. A threshold lets retrieval return fewer or no passages so the model can say it does not know. Score ranges depend on the embedding model and similarity metric, so a value must be calibrated on your own relevant and irrelevant examples.