Slides · Retrieval-augmented generation

Better retrieval

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:

  1. Walk a bad answer back to the failing stage.
  2. Combine hybrid search and reranking, and state what each costs.
  3. Choose a query transformation for a failure.
  4. Explain why filters run before or during search.
  5. Shape chunks and assemble context to improve the prompt.

Concept

A two-step search party

  1. A wide net brings in many candidates cheaply, so the right one is probably in the catch. This is recall.
  2. 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

Diagram: The query goes to dense search and BM25 in parallel, each returning a top 50.

Query

Dense
top 50

BM25
top 50

RRF
fusion

Cross-encoder
top 5

Prompt

Diagram summary: The query goes to dense search and BM25 in parallel, each returning a top 50. RRF fuses the two lists, a cross-encoder reranks the fused list down to the top 5, and those go into the prompt. The 50 and 5 are illustrative.

Compare

Each retriever has a blind spot

QueryDense (meaning)BM25 (exact words)
“How do I get my money back?” (document says “refund”)Finds it: paraphraseLikely misses: shares no key terms
“KX-9917-B won’t pair” (a part number, invented)May return general pairing pagesFinds 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

AspectRRFWeighted sum of normalised scores
UsesRanks onlyScores, rescaled to a common range
Needs score calibrationNoYes
TuningOne constant, k=60k = 60 by defaultWeights per retriever; needs labelled data
StrengthWorks out of the boxCan do better when tuned
  • RRFscore(d)=∑lists1k+rank(d)\mathrm{RRFscore}(d) = \sum_{\text{lists}} \dfrac{1}{k + \mathrm{rank}(d)}. Cormack, Clarke and Buettcher fixed k=60k = 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 kk 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.

Sources1 Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods2 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.

DocRanks (dense, BM25, paraphrase)Score
B2, 1, 1162+161+161=0.0489\frac{1}{62} + \frac{1}{61} + \frac{1}{61} = 0.0489
A1, 3, 2161+163+162=0.0484\frac{1}{61} + \frac{1}{63} + \frac{1}{62} = 0.0484
D-, 2, -162=0.0161\frac{1}{62} = 0.0161
C3, -, -163=0.0159\frac{1}{63} = 0.0159
E-, -, 3163=0.0159\frac{1}{63} = 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.

Source1 Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods

Diagram

Bi-encoder versus cross-encoder

Diagram: A bi-encoder embeds the query and each chunk separately, so chunk vectors can be computed in advance and compared cheaply.

Cross-encoder: reranking

Query + chunk together

One model call per pair

Relevance score

Bi-encoder: retrieval

Query

Encoder

Query vector

Chunk (precomputed)

Encoder

Chunk vector

Compare vectors

Diagram summary: A bi-encoder embeds the query and each chunk separately, so chunk vectors can be computed in advance and compared cheaply. A cross-encoder reads the query and one chunk together and scores the pair, which is more accurate but needs a model call for every pair, so it only runs on a shortlist.
  • 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.

Source3 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.

MeasurementQuestions with an answering chunkRate
In the shortlist of 50 (the ceiling)36 of 400.90
In the top 5 before reranking22 of 400.55
In the top 5 after reranking30 of 400.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.600.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

TechniqueWhat it doesUse whenCost or risk
RewriteLLM turns the query into a standalone searchFollow-ups like “what about the second one?”One LLM call; may change the meaning
Multi-querySeveral paraphrases, retrieve each, fuseShort or ambiguous queries; recall problemsSeveral searches; off-topic additions
DecompositionSplit into sub-questionsMulti-part or multi-hop questionsSeveral calls; sub-answers must be combined
Step-backAsk a more general question firstQuestions needing background principlesExtra call; can retrieve too broadly
HyDEEmbed an LLM-written hypothetical answerQuery and documents are phrased very differentlyThe invented answer can steer search toward a wrong idea
RoutingPick an index or tool by query typeSeveral corpora or mixed dataMisrouting 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

Diagram: A quick check decides whether a transform is needed.

no

follow-up

vague

multi-part

odd wording

User query

Needs a transform?
quick check

Retrieve

Rewrite

Multi-query

Decompose

HyDE

Diagram summary: A quick check decides whether a transform is needed. On “no” (the query is already precise) it is retrieved as is. Follow-ups are rewritten into standalone queries, vague queries get several paraphrases that are fused, multi-part questions are split, and queries worded unlike the documents (“odd wording”) can use a hypothetical answer. Every transform costs an extra call, and multi-query can hurt a precise query by diluting it.

Concept

HyDE: search with a hypothetical answer

  1. An instruction-following model writes a hypothetical document that answers the query. It may contain false details.
  2. An encoder embeds that document into a vector.
  3. 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.

Source4 Precise Zero-Shot Dense Retrieval without Relevance Labels

Worked example

Three failures, three fixes (invented examples)

FailureRaw queryFixTransformed 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

Diagram: The user sends a question with a session token.
Vector storeApp serverUserVector storeApp serverUserQuestion + session tokenRead tenant and groups from the verified tokenSearch with filter (tenant, groups, current version)Top-k from allowed chunks onlyAnswer built from those chunks
Diagram summary: The user sends a question with a session token. The server reads the tenant and groups from the verified identity, never from the question text, and sends them to the vector store as a filter on the search itself. The store returns the top-k from allowed chunks only.
  • 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

ApproachUpsideDownside
Post-filterSimple to bolt onCan return fewer than k results, or none; restricted text touches scores and logs
Pre-filter or in-query filterFull k results from allowed chunks; restricted chunks never fetchedIn 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_search of 40, a condition matching 10% of rows yields about 4 rows on average (40×0.1040 \times 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.

Source5 pgvector: open-source vector similarity search for Postgres

Compare

Chunk-level improvements

TechniqueIdeaCost
Parent-child (small-to-big)Match on small chunks, return the larger parentLarger prompts; de-duplicate shared parents
Sentence windowMatch one sentence, return it with N neighbours each sideSlightly larger prompts
Contextual chunksRestore the chunk’s context before indexing: a cheap title and section prefix, or an LLM-written noteThe note costs a model call per chunk at ingest
Structure-aware splittingRespect headings, tables, code blocksNeeds good parsing
Diversity (MMR)Trade relevance against redundancyAnother 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.

Source6 Introducing Contextual Retrieval

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=arg⁡max⁡d ∉ selected  [λ⋅sim(d,query)−(1−λ)⋅max⁡s∈selectedsim(d,s)]\text{next} = \underset{d \,\notin\, \text{selected}}{\arg\max}\; \Big[ \lambda \cdot \mathrm{sim}(d, \text{query}) - (1 - \lambda) \cdot \max_{s \in \text{selected}} \mathrm{sim}(d, s) \Big]
SymbolMeaning
ddA candidate chunk not yet selected
sim(d,query)\mathrm{sim}(d, \text{query})Relevance of the candidate to the query
max⁡s∈selectedsim(d,s)\max_{s \in \text{selected}} \mathrm{sim}(d, s)Similarity to the most similar chunk already chosen (redundancy)
λ\lambdaTrade-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.

Source7 The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries

Worked example

MMR with numbers (similarities are illustrative)

λ=0.7\lambda = 0.7. Chunk A is the most relevant and is picked first. Next, B and C compete:

Candidatesim to queryMax sim to selected (A)MMR score
B (near-duplicate of A)0.880.950.7×0.88−0.3×0.95=0.616−0.285=0.3310.7 \times 0.88 - 0.3 \times 0.95 = 0.616 - 0.285 = 0.331
C (different angle)0.800.300.7×0.80−0.3×0.30=0.560−0.090=0.4700.7 \times 0.80 - 0.3 \times 0.30 = 0.560 - 0.090 = 0.470
  • Plain ranking would pick B second, since 0.88>0.800.88 > 0.80. MMR picks C (0.470>0.3310.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.

Source7 The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries

Diagram

Context assembly: the last step before generation

Diagram: Context assembly removes duplicates, orders by relevance, stops at the token budget, places the strongest chunks at the start and end of...

Retrieved chunks

De-duplicate

Order by relevance

Cap at a token budget

Place strongest at start and end

Attach source ids

Final prompt

Optional: compress to relevant sentences

Diagram summary: Context assembly removes duplicates, orders by relevance, stops at the token budget, places the strongest chunks at the start and end of the context, and attaches source ids so the model can cite. Optional compression keeps only relevant sentences, at the risk of dropping one the answer needed.

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).

StepResult
De-duplicateDrop R2. Remaining: R1 400, R3 500, R4 450, R5 300
Cap at 1,500 tokens400+500+450=1,350400 + 500 + 450 = 1{,}350 fits; adding R5 gives 1,6501{,}650, over budget, so stop
PlaceBest 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.

Source8 Lost in the Middle: How Language Models Use Long Contexts

Diagram

Debugging playbook

Diagram: A decision tree for a bad answer: check the passage is indexed, then that it was retrieved, then that it survived reranking and trimming...

No

Yes

No

Yes

No

Yes

No

Yes

Bad answer

Passage in the
corpus and indexed?

Ingestion bug:
parse, missing doc, stale

In retrieved
top-k?

Retrieval bug: chunking,
embedding, hybrid, filters

In final prompt after
rerank and trimming?

Rerank or
budget bug

Answer follows
the passage?

Generation bug:
prompt, model, noise

Source or question
ambiguity

Diagram summary: A decision tree for a bad answer: check the passage is indexed, then that it was retrieved, then that it survived reranking and trimming into the prompt, then whether the answer follows it. The first “no” names the failing stage.
  • 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)

ReportWhat the logs showFailing stageFirst fix to try
“It cites the 2023 price”2025 page in the index; 2023 chunk retrieved at rank 1Versioning: metadata missing at ingest, no version filter at retrievalAdd date or version metadata at ingest and filter superseded chunks
“It can’t find ticket TK-5521”Answer chunk indexed; absent from dense top-50RetrievalAdd BM25 and fuse with RRF
“It ignores the refund rule”Rule chunk in the middle of a 12-chunk prompt; model answers from other chunksGeneration (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 9Retrieval diversityMMR, 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.

Source8 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

  1. Filters and chunk fixes. No extra runtime calls.
  2. Hybrid search. A second search and a cheap merge.
  3. Reranking. A model call per shortlisted chunk.
  4. 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=60k = 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)

  1. Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods (opens in a new tab)

    Gordon V. Cormack, Charles L. A. Clarke, Stefan Büttcher2009SIGIR 2009Paper

    Used for The RRF formula, k = 60 fixed in a pilot investigation, and the note that the choice was not critical.

  2. Retrieve & Re-Rank (opens in a new tab)

    Sentence Transformers2026Documentation

    Used for Bi-encoder retrieval followed by cross-encoder re-ranking, and why scoring millions of pairs with a cross-encoder is too slow.

  3. Precise Zero-Shot Dense Retrieval without Relevance Labels (opens in a new tab)

    Luyu Gao, Xueguang Ma, Jimmy Lin, Jamie Callan2023ACL 2023Paper

    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.

  4. pgvector: open-source vector similarity search for Postgres (opens in a new tab)

    pgvector2026Repository

    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)

  1. Introducing Contextual Retrieval (opens in a new tab)

    Anthropic2024Article

    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%.

  2. The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries (opens in a new tab)

    Jaime Carbonell, Jade Goldstein1998SIGIR 1998Paper

    Used for Maximal Marginal Relevance as a way to combine query relevance with novelty when reranking documents.

  3. 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

    Used for Models use information at the beginning or end of a long input better than information in the middle.