Slides · Retrieval-augmented generation
Better retrieval
1 / 29
Better retrieval
How to get the right chunk into the prompt more often: hybrid search, reranking, query fixes, filters, chunk shaping, careful context assembly, and a playbook for debugging a bad answer.
Concept
The best page was on page two
- The right policy page is in the knowledge base, listed on page two of the results. Kavya takes the top two results and says “that’ll do”. From where she sits, nobody can tell the best page was ever in the results.
- Many “the LLM hallucinated” bugs are really “the right chunk never reached the prompt”. Fixing the generator will not help if its evidence is wrong.
- Every technique here costs latency, money or complexity. The skill is applying the cheapest fix to the failure you have measured.
Five things you will be able to do:
- Walk a bad answer back to the failing stage.
- Combine hybrid search and reranking, and state what each costs.
- Choose a query transformation for a failure.
- Explain why filters run before or during search.
- Shape chunks and assemble context to improve the prompt.
Concept
A two-step search party
- A wide net brings in many candidates cheaply, so the right one is probably in the catch. This is recall.
- A careful sorter looks closely at each candidate and keeps the best few. This is precision.
Every technique in this lesson widens the net, sharpens the sorter, or cleans up what is handed over. Knowing which one a failure needs is the skill.
Diagram
Hybrid search then rerank
Compare
Each retriever has a blind spot
| Query | Dense (meaning) | BM25 (exact words) |
|---|---|---|
| “How do I get my money back?” (document says “refund”) | Finds it: paraphrase | Likely misses: shares no key terms |
| “KX-9917-B won’t pair” (a part number, invented) | May return general pairing pages | Finds the page that contains the exact string |
- Hybrid runs both and merges the lists, so each covers the other’s miss.
- The cost: two searches per query, and a merge step you now have to get right.
Compare
Two ways to merge: RRF or a weighted sum
| Aspect | RRF | Weighted sum of normalised scores |
|---|---|---|
| Uses | Ranks only | Scores, rescaled to a common range |
| Needs score calibration | No | Yes |
| Tuning | One constant, k=60 by default | Weights per retriever; needs labelled data |
| Strength | Works out of the box | Can do better when tuned |
- RRFscore(d)=∑listsk+rank(d)1. Cormack, Clarke and Buettcher fixed k=60 in a pilot investigation; the choice was not critical in their data.
- Elastic’s hybrid-search article notes RRF does not require score calibration or normalisation, and also that tuning k is not trivial and ranking quality can be affected by increasing result set size.
- A tuned weighted sum can beat untuned RRF, but it needs labelled data. Start with RRF and move only if you measure a gap.
Sources[1] Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods[2] Elasticsearch hybrid search
Worked example
RRF over three lists (k = 60)
Dense returns A, B, C. BM25 returns B, D, A. A third list (a paraphrase of the query, as in multi-query) returns B, A, E.
| Doc | Ranks (dense, BM25, paraphrase) | Score |
|---|---|---|
| B | 2, 1, 1 | 621+611+611=0.0489 |
| A | 1, 3, 2 | 611+631+621=0.0484 |
| D | -, 2, - | 621=0.0161 |
| C | 3, -, - | 631=0.0159 |
| E | -, -, 3 | 631=0.0159 |
- Fused order: B, A, D, then C and E tied.
- Both B and A appear in all three lists. B wins on better ranks overall (2, 1, 1 against 1, 3, 2), even though A was first in the dense list.
- Documents seen in only one list stay far behind: agreement between retrievers is what RRF rewards.
Source[1] Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods
Diagram
Bi-encoder versus cross-encoder
- The Sentence Transformers docs describe the same split: the cross-encoder outputs a single relevance score between 0 and 1 for a (query, document) pair.
Source[3] Retrieve & Re-Rank
Worked example
What reranking can and cannot fix
Illustrative experiment: 40 labelled questions, a shortlist of 50 from hybrid search, then rerank to 5.
| Measurement | Questions with an answering chunk | Rate |
|---|---|---|
| In the shortlist of 50 (the ceiling) | 36 of 40 | 0.90 |
| In the top 5 before reranking | 22 of 40 | 0.55 |
| In the top 5 after reranking | 30 of 40 | 0.75 |
- Reranking lifted the top-5 rate from 0.55 to 0.75, a gain of 8 questions. It can never exceed 0.90, because 4 questions had no answering chunk in the shortlist.
- To raise the ceiling, widen the shortlist, add hybrid search, fix chunking or transform the query. Reranking only reorders.
- The cost of the gain: a model call per shortlisted chunk, on every request. Measure on your own set before you adopt it.
Check yourself
Check: is the reranker worth keeping?
On a labelled set, a reranker lifts the top-5 hit rate from 0.60 to 0.72, but median response time doubles from 1.0 s to 2.0 s (illustrative numbers). The product is an internal tool where answers are read, not typed against a clock. When would you keep it, and what would you try before dropping it?
Answer
The gain is 12 points (0.72−0.60) for twice the latency. Keep it if the extra second is acceptable to users and wrong answers are costly, which is plausible for an internal tool. Before dropping it, try a smaller shortlist (fewer pairs to score), a smaller reranker, or reranking only when the first-stage scores look uncertain. Re-measure the hit rate and the latency after each change.
Compare
Fix the query instead of the index
| Technique | What it does | Use when | Cost or risk |
|---|---|---|---|
| Rewrite | LLM turns the query into a standalone search | Follow-ups like “what about the second one?” | One LLM call; may change the meaning |
| Multi-query | Several paraphrases, retrieve each, fuse | Short or ambiguous queries; recall problems | Several searches; off-topic additions |
| Decomposition | Split into sub-questions | Multi-part or multi-hop questions | Several calls; sub-answers must be combined |
| Step-back | Ask a more general question first | Questions needing background principles | Extra call; can retrieve too broadly |
| HyDE | Embed an LLM-written hypothetical answer | Query and documents are phrased very differently | The invented answer can steer search toward a wrong idea |
| Routing | Pick an index or tool by query type | Several corpora or mixed data | Misrouting sends queries to the wrong place |
Every transform adds an LLM call (latency and cost) and can drift from the user’s intent.
Diagram
Gate the transforms
Concept
HyDE: search with a hypothetical answer
- An instruction-following model writes a hypothetical document that answers the query. It may contain false details.
- An encoder embeds that document into a vector.
- The vector is used to find real documents that are similar to it.
Gao et al. (a 2022 preprint, published at ACL 2023) say the encoder’s dense bottleneck is what filters out the hypothetical document’s wrong details, grounding it in the real corpus, and report that the approach outperforms an unsupervised retriever baseline without needing relevance labels.
- Use it when queries look nothing like the documents (short questions against long technical text).
- Risk: if the hypothetical answer is wrong in a confident way, it steers the search toward the wrong area. It also costs one generation per query.
Source[4] Precise Zero-Shot Dense Retrieval without Relevance Labels
Worked example
Three failures, three fixes (invented examples)
| Failure | Raw query | Fix | Transformed query or queries |
|---|---|---|---|
| Follow-up lacks context | “what about the second one?” | Rewrite, using the chat history | “What is the refund window for the Silver plan?” |
| Short and ambiguous | “bank hours” | Multi-query | “bank opening hours”, “branch timings on weekends”, “customer service desk hours” |
| Two questions in one | “Compare the Gold and Silver refund windows and say which has the lower fee” | Decompose | “Gold refund window?”, “Silver refund window?”, “Gold fee?”, “Silver fee?” |
- Cost, per case: one LLM call; one call plus three searches; one call plus four searches and a step to combine the answers.
- The multi-query results are merged with RRF, as in the three-list slide.
- Precise queries such as an exact policy number should skip all of this.
Check yourself
Check: pick a transform
A user asks: “How do the vacation rules differ for contractors and for full-time staff, and who approves each?” Retrieval on the whole sentence returns a mix of pages, none complete. Which transform fits, and what does it cost?
Answer
Decomposition: the question has several parts (rules and approver, for two groups). Split it into sub-questions, retrieve for each, then combine the answers. The cost is several LLM calls and searches, and a combine step that must not lose any sub-answer.
Diagram
Where the filter value comes from
- Pre-filter (before or during search): the top-k is drawn from allowed chunks.
- Post-filter (after): the top-k can be mostly removed, leaving few or zero results.
- Some stores offer a namespace per tenant, which makes the restriction part of the search.
Compare
Filters have trade-offs too
| Approach | Upside | Downside |
|---|---|---|
| Post-filter | Simple to bolt on | Can return fewer than k results, or none; restricted text touches scores and logs |
| Pre-filter or in-query filter | Full k results from allowed chunks; restricted chunks never fetched | In some approximate indexes it can hurt recall or latency; know your database |
- The pgvector README is a concrete case: approximate indexes apply filtering after the index scan, so with HNSW and the default
hnsw.ef_searchof 40, a condition matching 10% of rows yields about 4 rows on average (40×0.10). It recommends iterative index scans, partial indexes (few distinct values) or partitioning (many values). - Permissions are enforced in the retriever. Asking the LLM to hide things is not a control, because the text is already in the prompt.
- Store source, date, document type, language, tenant and access list as metadata at ingest.
Source[5] pgvector: open-source vector similarity search for Postgres
Compare
Chunk-level improvements
| Technique | Idea | Cost |
|---|---|---|
| Parent-child (small-to-big) | Match on small chunks, return the larger parent | Larger prompts; de-duplicate shared parents |
| Sentence window | Match one sentence, return it with N neighbours each side | Slightly larger prompts |
| Contextual chunks | Restore the chunk’s context before indexing: a cheap title and section prefix, or an LLM-written note | The note costs a model call per chunk at ingest |
| Structure-aware splitting | Respect headings, tables, code blocks | Needs good parsing |
| Diversity (MMR) | Trade relevance against redundancy | Another scoring pass and a tuning parameter |
- The LLM-written note is what Anthropic calls contextual retrieval. It is applied to both the embeddings and the BM25 index. Their post reports a 49% lower top-20 failure rate for contextual embeddings plus contextual BM25 (5.7% to 2.9%) on their own datasets.
Math
Maximal marginal relevance (MMR)
Problem: the top 5 can be five copies of the same paragraph. MMR, from Carbonell and Goldstein (SIGIR 1998), combines query relevance with novelty. The form below is the commonly written one (this deck’s cited page is the paper’s abstract, so check the formula in the paper itself):
next=d∈/selectedargmax[λ⋅sim(d,query)−(1−λ)⋅s∈selectedmaxsim(d,s)]| Symbol | Meaning |
|---|---|
| d | A candidate chunk not yet selected |
| sim(d,query) | Relevance of the candidate to the query |
| maxs∈selectedsim(d,s) | Similarity to the most similar chunk already chosen (redundancy) |
| λ | Trade-off between 0 and 1: 1 means relevance only, 0 means diversity only |
- Pick the first chunk by relevance alone. Each later pick must be relevant and different from what you already have.
Source[7] The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries
Worked example
MMR with numbers (similarities are illustrative)
λ=0.7. Chunk A is the most relevant and is picked first. Next, B and C compete:
| Candidate | sim to query | Max sim to selected (A) | MMR score |
|---|---|---|---|
| B (near-duplicate of A) | 0.88 | 0.95 | 0.7×0.88−0.3×0.95=0.616−0.285=0.331 |
| C (different angle) | 0.80 | 0.30 | 0.7×0.80−0.3×0.30=0.560−0.090=0.470 |
- Plain ranking would pick B second, since 0.88>0.80. MMR picks C (0.470>0.331).
- The prompt now carries two distinct pieces of evidence instead of the same paragraph twice.
- Cost: a tuning parameter. With lambda too low you pick diverse but weakly relevant chunks.
Source[7] The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries
Diagram
Context assembly: the last step before generation
Worked example
Assembling a 1,500-token context (illustrative)
Five reranked chunks arrive, in relevance order: R1 (400 tokens), R2 (350, a near-copy of R1), R3 (500), R4 (450), R5 (300).
| Step | Result |
|---|---|
| De-duplicate | Drop R2. Remaining: R1 400, R3 500, R4 450, R5 300 |
| Cap at 1,500 tokens | 400+500+450=1,350 fits; adding R5 gives 1,650, over budget, so stop |
| Place | Best first, next best last, the third in the middle: R1, R4, R3 |
- Liu et al. (2023) found models use information at the start and end of a long input better than the middle. Their tests used much longer inputs than this 1,350-token example, so treat this as a heuristic for long prompts and check it on your own model.
- The R5 drop is a quiet failure: retrieval looks fine, but the chunk never reaches the model. Log what was cut.
- The placement rule is a heuristic from that finding. Check it on your own model.
Source[8] Lost in the Middle: How Language Models Use Long Contexts
Diagram
Debugging playbook
- Separation test: paste the gold passage into the prompt by hand. A correct answer means retrieval or ingestion failed. A wrong answer means generation or the prompt.
- Log the retrieved chunk ids for every request. Without them this tree cannot be walked after the fact.
Worked example
Playbook in use (illustrative logs)
| Report | What the logs show | Failing stage | First fix to try |
|---|---|---|---|
| “It cites the 2023 price” | 2025 page in the index; 2023 chunk retrieved at rank 1 | Versioning: metadata missing at ingest, no version filter at retrieval | Add date or version metadata at ingest and filter superseded chunks |
| “It can’t find ticket TK-5521” | Answer chunk indexed; absent from dense top-50 | Retrieval | Add BM25 and fuse with RRF |
| “It ignores the refund rule” | Rule chunk in the middle of a 12-chunk prompt; model answers from other chunks | Generation (prompt context placement) | Cap the budget, move the best chunks first and last (Liu et al., 2023), then re-test |
| “It misses the policy exception” | Top 5 are the same two paragraphs repeated across three document versions; the exception chunk sits at rank 9 | Retrieval diversity | MMR, or de-duplicate before assembly |
- One question at a time, in pipeline order. The first “no” is where you work.
- Match the fix to the measured failure, not to a favourite technique.
Source[8] Lost in the Middle: How Language Models Use Long Contexts
Check yourself
Check: content from the wrong plan
A support lead says: “The assistant told a customer something that only applies to enterprise accounts.” Logs show the enterprise-only chunk was retrieved for a free-tier user. Which stage and which fix?
Answer
Retrieval, specifically the filter: the chunk should never have been a candidate for this user. Check that the free-tier user’s plan or group reaches the search as a filter, that it comes from the verified identity and not from the question, and that the chunk carries the right access metadata. Fix the filter, not the prompt: telling the model to ignore enterprise content is not a control.
Process
Add techniques in order of cost
- Filters and chunk fixes. No extra runtime calls.
- Hybrid search. A second search and a cheap merge.
- Reranking. A model call per shortlisted chunk.
- Query transforms last. They add an LLM call to every request they run on.
Justify each step with a failure you measured on a labelled set, and gate expensive steps so they only run when needed.
Summary
Recap
- Quality is capped by retrieval. The right chunk must reach the prompt.
- Hybrid is dense plus BM25, fused by RRF (k=60 default, rank-based). Reranking gives precision at a latency cost and cannot exceed the shortlist.
- Query transforms fix the query but add a call and can drift. Gate them.
- Filter by metadata and permissions before or during search, with values from the verified identity.
- Parent-child, sentence windows, contextual chunks and MMR improve what is retrieved. Assembly decides what the model sees.
- Log retrieved chunk ids and walk the debugging tree from the symptom back.
References
References & Sources (1 of 2)
Gordon V. Cormack, Charles L. A. Clarke, Stefan Büttcher2009SIGIR 2009Paper
https://cormack.uwaterloo.ca/cormacksigir09-rrf.pdf
Used for The RRF formula, k = 60 fixed in a pilot investigation, and the note that the choice was not critical.
Elasticsearch hybrid search (opens in a new tab)
Valentin Crettaz2025Article
https://www.elastic.co/search-labs/blog/hybrid-search-elasticsearch
Used for RRF needs no score calibration or normalisation; tuning the constant is not trivial and quality can suffer as the result set grows.
Retrieve & Re-Rank (opens in a new tab)
Sentence Transformers2026Documentation
https://sbert.net/examples/applications/retrieve_rerank/README.html
Used for Bi-encoder retrieval followed by cross-encoder re-ranking, and why scoring millions of pairs with a cross-encoder is too slow.
Precise Zero-Shot Dense Retrieval without Relevance Labels (opens in a new tab)
Luyu Gao, Xueguang Ma, Jimmy Lin, Jamie Callan2023ACL 2023Paper
arXiv 2212.10496 (opens in a new tab)https://arxiv.org/abs/2212.10496
Used for HyDE: embed an LLM-written hypothetical document and retrieve real documents near it, with the generated text's incorrect details filtered by the encoder.
pgvector: open-source vector similarity search for Postgres (opens in a new tab)
pgvector2026Repository
https://github.com/pgvector/pgvector
Used for Approximate indexes filter after the index scan, so a selective condition can return fewer rows (about 4 for a 10% condition at ef_search 40); iterative scans, partial indexes and partitioning.
References
References & Sources (2 of 2)
Introducing Contextual Retrieval (opens in a new tab)
Anthropic2024Article
https://www.anthropic.com/news/contextual-retrieval
Used for Contextual retrieval applied to both embeddings and BM25, and the reported drop in top-20 failure rate from 5.7% to 2.9%.
Jaime Carbonell, Jade Goldstein1998SIGIR 1998Paper
https://people.eng.unimelb.edu.au/ammoffat/sigir98/abstracts/carbonell.html
Used for Maximal Marginal Relevance as a way to combine query relevance with novelty when reranking documents.
Lost in the Middle: How Language Models Use Long Contexts (opens in a new tab)
Nelson F. Liu, Kevin Lin, John Hewitt, Ashwin Paranjape, et al.2023Transactions of the Association for Computational Linguistics (TACL)Paper
arXiv 2307.03172 (opens in a new tab)https://arxiv.org/abs/2307.03172
Used for Models use information at the beginning or end of a long input better than information in the middle.
Keys: ← → move, Home End first and last, F full screen.