Advanced RAG: improving the query, the search, and the context
Advanced RAG adds work before, during, and after retrieval: rewrite the query, search by keyword and meaning, rerank, compress, and check the answer. Use it when simple RAG finds the wrong passages.
Advanced RAG in 60 seconds
- What: the single-pass pipeline plus extra stages before retrieval (rewrite, filter), during it (hybrid search), and after it (rerank, compress, check).
- Why: each stage fixes a specific failure of plain similarity search, so retrieved text becomes more relevant and the answer more reliable.
- Best for: large or messy document sets, mixed vocabulary, and answers that carry real consequences.
- Costs: more latency, more components to run, and more places for bugs to hide.
- Source of the idea: a widely cited survey (Gao et al., 2023) groups these upgrades as pre-retrieval, retrieval, and post-retrieval improvements.
Where this type fits
Advanced RAG belongs to the quality-loop family with corrective RAG, self-RAG, and HyDE. These types spend extra effort to make retrieved text better or to check it. Advanced RAG is the most general of them: a pipeline with extra stages, usually still a straight line. The overview of RAG types shows how the family relates to the others.
The problem it solves
Simple RAG assumes that the user's question, matched by meaning against chunks, will find the right chunks. That assumption fails in predictable ways. The question is short or vague, so its embedding is vague too. The question uses an exact code, such as an error number or product SKU, and embeddings blur exact strings. The top five results include four near-duplicates and one useful chunk. Or the useful chunk is in the top twenty but not the top five.
Each failure has a matching repair, and advanced RAG is the collection of those repairs. Rewrite the query so it is clearer. Search by keyword as well as by meaning. Fetch more candidates than you need, then rank them with a stronger method. Trim each passage to the sentences that matter. Finally, check that the answer is supported by what was retrieved.
A good analogy is a newsroom researcher. They do not accept the first page of search results. They rephrase the search, try exact names as well as topics, gather twenty articles, read the openings to pick the best five, highlight the relevant paragraphs, and then check the draft against the sources. None of those steps is clever alone, but together they change the result.
How it works
The survey behind this term sorts the upgrades into three groups. Here they are as a sequence.
- Before retrieval, rewrite and expand: turn the raw question into one or more better queries. Add synonyms, expand abbreviations, or split a compound question. Extract filters such as product, date, or language from the question.
- Before retrieval, index well: this happens offline. Use chunk boundaries that follow structure, and add metadata and short summaries so chunks can be found and filtered.
- During retrieval, hybrid search: run keyword search (which is good at exact terms) and vector search (which is good at meaning), then merge the two ranked lists. Take a generous number of candidates, such as 30.
- After retrieval, rerank: score each candidate against the query with a stronger model that reads query and passage together, then keep the top few.
- After retrieval, compress: cut each kept passage to the sentences that matter, and remove duplicates, so the prompt is short.
- Generate with rules: the prompt demands citations and permits 'I do not know'.
- Check the answer: verify that the main claims are supported by the passages, and retry or decline if they are not. Give the retry a hard limit.
The key idea in the middle of the diagram is the two-stage funnel. The first stage must be fast, because it looks at the whole index, so it uses approximate methods that return a wide set. The second stage can be slow and precise, because it only looks at a few dozen candidates. This is why a reranker is affordable: it never sees the full corpus.
Hybrid search merges the two lists by rank rather than by raw score, because keyword scores and vector similarities are on different scales. A common approach gives each candidate a score based on its position in each list and adds them. Candidates that rank well in both lists rise to the top, which is the behaviour you want.
A worked example
Acme Outdoors runs a support bot over 8,000 chunks of product manuals. A customer asks: 'Stove keeps showing E14 after I changed the gas, what now?'
- Rewrite: the query becomes two: 'portable stove error code E14 meaning and fix' and 'stove fault after replacing gas canister'. The filter
doc_type: manualis added, since the question is about troubleshooting. - Hybrid search: keyword search finds chunks that contain 'E14' exactly, which pure vector search had missed. Vector search finds chunks about gas pressure faults. The lists are merged into 30 candidates.
- Rerank: a reranker reads the question with each candidate. The chunk 'E14: low gas pressure. Check the canister seal and re-seat the regulator' rises to first. A chunk about E41 for a different model drops from second to twentieth.
- Compress: the top four chunks are trimmed to the few sentences about E14 and canister seals. The prompt falls from about 2,000 tokens to about 500.
- Generate: the model writes: 'E14 means low gas pressure. Re-seat the canister and check the seal [1]. If the code stays, contact support [2].'
- Check: a verification step confirms that both claims appear in the cited chunks. It passes, and the answer is returned.
before = [ # merged hybrid list, position by position
('stove-e41-model-b', 0.78),
('stove-gas-types', 0.74),
('stove-e14-low-pressure', 0.71),
]
after = [ # reranker score, query and chunk read together
('stove-e14-low-pressure', 0.93),
('stove-gas-types', 0.41),
('stove-e41-model-b', 0.12),
]
Each stage contributed something different. The rewrite and the filter narrowed the field, the keyword half found the exact code, the reranker fixed the order, and compression kept the prompt cheap. Remove any one and the answer still might be acceptable, which is why you should measure each stage before keeping it.
Building it
The code wires the stages together. rewrite_llm, keyword_index, vector_store, rerank(), compress(), llm, and verify() are placeholders. The structure to notice is that every stage is a plain function, and the retry loop has a fixed upper bound.
# Illustrative only. All helpers named below are placeholders.
CANDIDATES = 30 # wide net for the first stage
KEEP = 4 # what the model actually reads
MAX_ATTEMPTS = 2 # one answer plus at most one retry
TIMEOUT_SECONDS = 20
def rewrite(question):
# Returns a list of queries and a metadata filter, for example
# (['stove error E14 fix', 'stove fault after gas change'], {'doc_type': 'manual'})
return rewrite_llm.expand(question) # placeholder
def rank_fusion(lists, k=60):
# Merge ranked lists by position, because raw scores are on different scales.
scores = {}
for ranked in lists:
for position, doc_id in enumerate(ranked, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + position)
return sorted(scores, key=scores.get, reverse=True)
def retrieve(question, user):
queries, meta_filter = rewrite(question)
meta_filter['audience'] = user.allowed_audiences # permissions always applied
lists = []
for q in queries:
lists.append(keyword_index.search(q, top_k=CANDIDATES, filter=meta_filter))
lists.append(vector_store.search(embed(q), top_k=CANDIDATES, filter=meta_filter))
merged = rank_fusion(lists)[:CANDIDATES]
ranked = rerank(question, merged) # placeholder cross-reading model
return [compress(question, c) for c in ranked[:KEEP]]
def advanced_rag(question, user):
passages = retrieve(question, user)
if not passages:
return 'I could not find this in the documentation.'
for attempt in range(MAX_ATTEMPTS):
answer = llm.generate(question, passages, timeout=TIMEOUT_SECONDS) # placeholder
# verify() returns True when each claim is supported by the passages.
if verify(answer, passages):
return answer
# On failure, retry once with stricter instructions, then give up.
passages = passages[:2] # fewer, higher-ranked passages
return 'I am not confident in an answer. Please contact support.'
The final fallback matters as much as the happy path. When the check fails twice, the system says so instead of returning a doubtful answer. That is a product decision, and it is easy to encode when the stages are explicit.
Design decisions
- Add stages one at a time: start from simple RAG and add the stage that fixes your biggest measured failure. Default: hybrid search first, then reranking, then rewriting. Each should earn its place on your evaluation set.
- Candidate depth: retrieve 20 to 50 candidates and keep 3 to 6 after reranking. Too few candidates caps recall, and too many makes reranking slow.
- Reranker placement and model: run it as its own service with a latency budget. A smaller reranker may be adequate, and you can cache scores for popular queries. See caching types.
- Storage: you now run a keyword index and a vector index. Either use one engine that does both, or keep them in sync from the same ingestion pipeline. See indexing.
- Access control: apply permission filters in both searches, and again before compression. A stage that rewrites queries must never be allowed to drop the permission filter.
- Failure handling: every stage needs a timeout and a fallback. If reranking fails, use the merged order. If rewriting fails, use the raw query. Retries on the answer check must be capped.
- Versioning and cost: pin the versions of the rewrite prompt, the reranker, and the index together, and log the version with every answer. Count model calls per request, since stages multiply them.
Measuring it
- Stage-by-stage recall: measure recall at 30 after hybrid search, then precision at 4 after reranking. If recall at 30 is low, no reranker can help.
- nDCG or reciprocal rank after reranking: compare the ranking against labelled relevance to see whether the order improved. Report the gain over the merged list.
- Compression loss: check that the answer-bearing sentence survives compression. Count questions where the needed sentence was trimmed away.
- End-to-end faithfulness and correctness: compare with the simple RAG baseline on the same questions, and report the change per stage in an ablation table (turn each stage off in turn).
- Latency and cost per answer: record the median and the 95th percentile, plus model calls per request. A quality gain that triples latency may not be worth it.
# run_pipeline(question, **flags) and score() are placeholders.
STAGES = ['rewrite', 'hybrid', 'rerank', 'compress', 'verify']
def ablation(test_set):
results = {'all_on': score(test_set, lambda q: run_pipeline(q))}
for stage in STAGES:
flags = {stage: False}
results['without_' + stage] = score(
test_set, lambda q: run_pipeline(q, **flags))
return results # a stage that changes nothing is a stage you can remove
When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| Simple RAG finds the wrong chunks on real questions | Yes | Hybrid search and reranking target exactly this failure. |
| Content has exact codes, names, or numbers | Yes | Keyword search catches what embeddings blur. |
| Large corpus with many near-duplicate passages | Yes | Reranking and compression remove redundancy. |
| Answers carry legal, financial, or safety weight | Yes | The answer check adds a safety net. |
| Small, clean document set and simple questions | No | Extra stages add cost without measurable gain. |
| Strict latency target under about a second | Maybe | Keep only the cheap stages, such as hybrid search. |
| Questions that need several steps or sources | Not alone | Consider agentic RAG or branched RAG. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Higher relevance and fewer unsupported answers when stages are well tuned. | Prove each stage with an ablation, and remove stages that do not help. |
| Latency | Each stage adds time, and rewriting, reranking, and checking can each involve a model call. | Run keyword and vector search in parallel, cap candidate counts, and skip stages for easy queries. |
| Cost | More model calls and bigger indexes per request. | Use small models for rewriting and reranking, and cache stable results. |
| Complexity | Several components to deploy, version, and monitor. | Define fixed interfaces between stages, which leads naturally to modular RAG. |
| Failure modes | A bad rewrite hides the right chunk, over-compression drops the key sentence, and a verifier can reject a good answer. | Log each stage's output, set fallbacks, and alert on stage-specific error rates. |
Compared with related types
Against simple RAG, advanced RAG is the same single pass with more care before and after the search. Against corrective RAG, it improves retrieved text in a fixed sequence, while corrective RAG grades the result and chooses a different action, such as discarding it and searching elsewhere. Against modular RAG, advanced RAG is a particular selection of stages, while modular RAG is the design discipline of making every stage swappable and measurable. Many teams build advanced RAG and discover they have built modular RAG on the way.
What this means for your role
Common mistakes
Further reading
- Gao et al., 2023: Retrieval-Augmented Generation for Large Language Models, a survey, which describes Naive, Advanced, and Modular RAG and the pre-retrieval, retrieval, and post-retrieval improvements.
- Vector search and chunking, for embeddings, chunk sizes, and hybrid search.
- Bloom filters and indexing, for background on fast first-stage lookups.
Advanced RAG is a toolbox, not a mandate. Reach for a stage when you can name the failure it fixes and show the gain it brings.