RAG Retrieving Irrelevant Chunks: Diagnose and Fix It
RAG retrieving irrelevant chunks is fixed by diagnosing first: log the top 50 chunks per query, then decide if the right chunk is missing (recall failure) or ranked too low (ranking failure), and apply the matching fix.
- Log the query, top 50 chunks, scores and metadata before changing anything, so you can tell a recall failure from a ranking failure.
- Build a golden set of 20 to 50 real questions mapped to correct chunks and track recall@k and MRR after every single change.
- Fix recall problems with cleaner data, better chunking, metadata filters, hybrid search and query rewriting.
- Fix ranking problems with a cross-encoder reranker over about 30 candidates, passing 3 to 8 chunks to the LLM.
- Change one thing at a time, and re-embed every document whenever you change chunking or the embedding model.
Why does my RAG pipeline retrieve irrelevant chunks?
Retrieval fails in only a few ways, and each leaves a different fingerprint. The right chunk may never reach the candidate list (recall failure). It may be in the list but buried under look-alikes (ranking failure). Or the query itself may be too vague to embed well.
Most teams skip straight to swapping the LLM or the vector database. That is usually wrong: if the correct passage is not in the prompt, no model can answer from it. Generation problems such as invented facts when the right context is present belong in the hallucination article, not here.
The rest of this page gives a fixed order: inspect, classify, fix, measure.
How do I diagnose a RAG retrieval problem step by step?
Do this before changing any setting. Pick 5 to 10 queries that failed, and for each one find by hand the chunk that should have matched.
- Log the raw query that was embedded (not the chat history), the top 50 chunks with scores, rank, source file, section and metadata.
- Find the chunk that should have matched and note its rank. If it is not in the top 30 (your candidate pool), it is a recall failure. A rank of 31 to 50 is a near miss that a larger pool or better filtering may fix.
- If it appears at rank 6 to 30, it is a ranking failure: the content is retrievable but scored below noise.
- Read the top 5 wrong chunks. Are they near-duplicates, boilerplate (headers, footers, legal text), the wrong version, or just the same topic?
- Check that the query string is what you expect. A common bug is embedding the whole conversation or a prompt template instead of the question.
How do I build a golden set and measure recall@k and MRR?
Judging by 2 or 3 queries is the most common reason fixes seem to work and then do not. Collect 20 to 50 real user questions and map each to the chunk IDs or document IDs that contain the answer. Include exact-code queries, vague follow-ups and version-specific questions, because those are where failures hide.
Recall@k is the share of questions where a correct chunk is in the top k. MRR is the average of 1/rank of the first correct chunk, so it rewards putting it near the top. Measure recall@30 to judge candidate generation and recall@5 or MRR to judge final ordering.
import json
def evaluate(golden, search, k=50, pool=30):
hits, rr, log = 0, 0.0, []
for item in golden: # {"q": str, "gold": [doc/chunk ids]}
results = search(item["q"], top_k=k) # [{id, score, source, text}]
ids = [r["id"] for r in results]
rank = next((i + 1 for i, x in enumerate(ids) if x in item["gold"]), None)
hits += rank is not None and rank <= pool
rr += 1 / rank if rank else 0
log.append({"q": item["q"], "rank": rank,
"top": [(r["id"], round(r["score"], 3), r["source"]) for r in results[:50]]})
n = len(golden)
print(f"recall@{pool}={hits/n:.2f} MRR={rr/n:.3f}")
with open("retrieval_log.json", "w") as f:
json.dump(log, f, indent=1) Which symptom needs which fix?
Use the rank of the correct chunk to pick the fix instead of trying every technique.
| Symptom | Likely cause | First fix |
|---|---|---|
| Right chunk not in the top 30 | Bad extraction, bad chunking, embedding mismatch, or vague query | Clean data, re-chunk with headings, verify the same model for index and query, rewrite the query |
| Right chunk at rank 6 to 30 | Ranking failure, many similar chunks | Add a cross-encoder reranker over 30 candidates |
| Right topic, wrong version or product | No metadata filtering | Tag chunks and pre-filter in the vector query |
| Exact codes, SKUs or error strings fail | Dense vectors blur rare tokens | Add BM25 and fuse with RRF |
| Same passage repeated several times | Near-duplicates or high overlap | Dedup at ingest, use MMR, lower overlap |
| Follow-ups like 'what about the price?' fail | Query lacks context | Rewrite into a standalone question using history |
How do I fix the data side: embeddings, chunking and metadata?
Start with the cheapest, highest-payoff checks. First, clean the text. PDF extraction often leaks page headers, footers, cookie banners and table fragments that make every chunk look alike. Strip them before embedding.
Embedding consistency: the index and the query must use the same model, version and dimension. Re-embedding only some documents after an update produces meaningless cross-comparisons. Confirm the distance metric matches the model (cosine, dot product or L2) and normalise vectors if the model expects it. Some models need prefixes: E5 expects 'query: ' and 'passage: ', and BGE uses an instruction for queries. Also check the model's max input tokens, because longer chunks are silently truncated and the tail is never searchable.
Chunking: chunks that are too small lose context, and chunks that are too large dilute the embedding. A good starting point is 200 to 500 tokens with 10 to 15% overlap, split on headings, paragraphs, list items and whole tables rather than a fixed character count. Prepend the document title and section heading to every chunk, so 'Refunds' text still says which product it belongs to. For long answers, try parent-child retrieval: match on small child chunks, then send the larger parent section to the LLM.
Metadata: tag each chunk with product, version, language, date, doc type and tenant or permission. Apply these as pre-filters inside the vector query, either set by the UI or inferred from the query.
{
"vector": [0.012, -0.044],
"top_k": 30,
"filter": {"product": "acme-pro", "version": "4.2", "lang": "en"}
}Hybrid search, reranking, top-k and query rewriting: how do I add them?
Hybrid search: pure dense retrieval misses exact terms such as product codes, error codes, names and acronyms. Run BM25 (keyword) and vector search in parallel and merge with Reciprocal Rank Fusion: score = sum of 1/(60 + rank) across lists. RRF needs no score normalisation, which is why it is the safe default. Native support exists in Elasticsearch and OpenSearch, Weaviate, Qdrant and Pinecone (sparse-dense), and on Postgres by combining full-text search with pgvector.
Reranking: a cross-encoder (Cohere Rerank, a BGE reranker or a Jina reranker) reads the query and each candidate together, so it judges relevance far better than vector distance. It is often the biggest single precision gain. Rerank about 30 candidates and pass the best 3 to 8 to the LLM. The cost is added latency (often tens to a few hundred milliseconds depending on model and hosting) and per-call fees or GPU time. Skip it when recall@5 is already high, the corpus is tiny, or latency is critical.
Top-k: too low drops the right chunk, too high floods the prompt with noise. The common pattern is retrieve 30, rerank, keep 5. Add a score threshold and allow a 'no good match' path rather than always filling every slot. Use MMR or dedup when near-duplicates crowd the list.
Query side: short follow-ups embed poorly. Use the chat history to rewrite them into a standalone question, then embed only that. Multi-query expansion (generate 3 paraphrases and fuse the results) and HyDE (embed a hypothetical answer) help when vocabulary differs between question and document.
def rrf(lists, k=60):
scores = {}
for results in lists: # each: ordered list of chunk ids
for rank, cid in enumerate(results, 1):
scores[cid] = scores.get(cid, 0) + 1 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
candidates = rrf([bm25_ids[:50], vector_ids[:50]])[:30]
final = rerank(query, candidates)[:5] What order should I apply fixes in, and what mistakes should I avoid?
Go by effort and payoff: inspect and clean data, then chunking and metadata, then hybrid search, then a reranker, then query rewriting, and only then swap the embedding model or fine-tune. Embedding swaps are expensive because they force a full re-index, and they rarely fix what better data would.
Avoid these mistakes: changing several things at once, so you cannot tell what helped; judging on 2 or 3 queries; blaming the LLM when retrieval is the problem; re-chunking without re-embedding; and ignoring stale indexes after documents are updated or deleted. Set up an update job that re-embeds changed files and removes deleted ones.
Rerun the golden set after every change and keep the log. If recall@30 is high but MRR is low, work on ranking. If recall@30 is low, work on data, chunking, filters or the query.
Common questions
What is the best chunk size for RAG?
Start with 200 to 500 tokens and 10 to 15% overlap, split on headings and paragraphs. Then test 2 or 3 sizes against your golden set, since the best value depends on how self-contained your documents are.
Hybrid search vs vector search: which is better for RAG?
Hybrid is usually better when users search for codes, names, SKUs or acronyms, because BM25 matches exact tokens that embeddings blur. For purely conversational questions over prose, vector search alone may already score well, so compare both on your golden set.
Does a reranker replace the need for good chunking?
No. A reranker can only reorder candidates that were retrieved, so it cannot rescue a recall failure. Fix chunking and candidate recall first, then add a reranker to sharpen the order.
How many chunks should I send to the LLM?
Usually 3 to 8 after reranking. More chunks add noise and cost and can bury the answer, while fewer risk missing it, so tune the number using answer quality on the golden set.
Why did retrieval get worse after I updated my documents?
Likely causes are a partial re-embed with a different model or settings, old chunks left in the index next to new ones, or missing metadata on new chunks. Re-embed consistently and delete stale chunks by document ID.