Skip to content

Chapter 2 · Advanced RAG

2.1 What problems does naive RAG have, and how does advanced RAG improve on it? ★★

One-sentence answer

Naive RAG retrieves the top-k once with the original question, pastes the results into the prompt as they are, and generates; it has typical failure modes at four stages: the query, the number of retrieval rounds, the index structure and the context. Advanced RAG keeps the "retrieve, then generate" backbone and optimizes the query before retrieval and the context after it; Modular RAG goes further and breaks the pipeline into freely composable modules, adding routing, iteration and multiple data sources.

I will address three aspects: which assumptions naive RAG makes implicitly, at which stages these assumptions break, and how advanced RAG and modular RAG improve on it.

(1) Naive RAG is the simplest "retrieve once, concatenate, generate" pipeline, and it rests on several overly strong assumptions.

The standard pipeline from Chapter 0 works like this: offline, the documents are split into chunks and indexed; online, the user's original question is used to retrieve the top-k chunks, which are concatenated into the prompt in order, and the LLM generates the answer. This pipeline is often called naive RAG. It is simple because it takes four things for granted: the user's question is itself a good retrieval query; a single retrieval finds all the information needed; the answer is concentrated in a few chunks; and the retrieved chunks, placed in the context as they are, will be used well by the model. In real scenarios, however, all four assumptions frequently fail, and each failed assumption corresponds to a class of failures.

(2) These assumptions break at four stages, each corresponding to a class of problems.

  • The query stage: The user's question is written for people. It may depend on the chat history, contain irrelevant details, ask several things at once, or be worded very differently from the documents, so retrieving with it directly works poorly (see 2.2).
  • The number of retrieval rounds: In a multi-hop question, the entity to look up next is only known after reading the documents from the previous step, so a single retrieval cannot find everything (see 2.3).
  • The index structure: Flat chunks can only answer local questions whose answer sits in one or two passages; they cannot answer global questions that require generalizing over the entire corpus (see 2.4).
  • The context stage: Too many retrieved results, with duplicates, noise and a poor order, distract the model and raise costs (see 2.5).

(3) Advanced RAG optimizes "before retrieval" and "after retrieval" while keeping the backbone, whereas modular RAG makes the pipeline modular.

The survey by Gao et al. (2023) divides the development of RAG into three stages: Naive RAG, Advanced RAG and Modular RAG. Advanced RAG is still a linear "retrieve, then generate" pipeline; it adds pre-processing such as query rewriting, HyDE and query decomposition before retrieval, and post-processing such as reranking, compression and reordering after retrieval. Modular RAG no longer fixes the shape of the pipeline: it turns functions such as search, routing, memory and rewriting into independent modules and allows conditional branches and loops, for example first deciding which data source a question should go to, or iterating several rounds between retrieval and generation. Going further in this direction leads to two separate topics: when to retrieve and how much (see Chapter 3), and letting the model act like an agent that decides for itself what to search for and how many times (see Chapter 5). It is important to stress that every added module brings another LLM call and another chance to go wrong, so improvements should start from error analysis and target the failure modes actually observed, rather than piling on every technique.

In summary: the essence of advanced RAG is adding a targeted module for each of naive RAG's failure modes at each stage, while modular RAG makes these modules composable as needed.

Problems and techniques by stage:

Stage Problem with naive RAG Techniques See
Before retrieval (the query) The question depends on context, is vague, has several parts, or is worded unlike the documents Query rewriting, HyDE, decomposition, multi-query 2.2
Retrieval rounds A single retrieval cannot follow a chain of facts Iterative retrieval, multi-hop retrieval (IRCoT) 2.3
Index structure Flat chunks cannot answer questions about the corpus as a whole GraphRAG, hierarchical summaries 2.4
After retrieval (the context) Too many results, noise and duplicates, poor order Reranking, deduplication, compression, reordering 2.5
Overall architecture Is retrieval still needed, or is a long context enough? Trading off and combining long context and RAG 2.6
Data type The facts live in tables and databases rather than text Table handling, text-to-SQL, routing 2.7

Going deeper: locating the stage where a failure happens

(1) First separate "not retrieved" from "retrieved but not used well".

For a batch of wrongly answered examples, first check whether the document containing the answer appears in the top-k, i.e. recall@k. If it does not, the problem lies before or in retrieval: if the question is worded very differently from the documents, consider query rewriting or HyDE; if the question has several parts or needs multiple hops, consider decomposition or iterative retrieval; if the question is global, the index structure needs to change. If the document is already in the top-k but the answer is still wrong, the problem lies after retrieval or in generation: if there is too much noise or the key document sits in the middle, consider reranking, compression and reordering; if the model is not faithful to the documents, this is the knowledge-conflict and faithfulness problem discussed in Chapter 4. Component-wise evaluation of RAG is covered in Chapter 6.

(2) The three-stage division is a categorization, not a specific method.

The Naive, Advanced and Modular stages are a division the survey made to organize a large body of work, and there are no strict boundaries between them. For example, Rewrite-Retrieve-Read (see 2.2) can be viewed either as query rewriting within advanced RAG or as one way of composing modules within modular RAG.

Follow-up questions

Follow-up 1: What is the difference between advanced RAG and modular RAG?

The difference is whether the shape of the pipeline is fixed. Advanced RAG is still a fixed linear pipeline with processing steps added before and after retrieval; modular RAG splits the functions into modules that can be replaced and recombined, supporting routing, conditional branches and loops, so different questions can take different paths.

Follow-up 2: If a production RAG system has a high error rate, how would you locate the problem?

Start with error attribution, separating retrieval failures from generation failures. Sample a batch of wrong answers and check whether the correct document is in the top-k: if it is not, improve the query, the retriever or the index; if it is, check whether the context is too long, whether the key information is buried in noise, and whether the model is faithful to the documents. Only by knowing which stage failed can you pick the right technique.

Follow-up 3: Is it better to add as many of these techniques as possible?

No. Every added module brings another LLM call, a few hundred milliseconds of latency and another chance to go wrong; for example, rewriting can misread the question, and compression can delete a key sentence. The right approach is to verify, one module at a time, on your own data and with both retrieval metrics and end-to-end metrics, whether each module actually helps.

Common mistakes

  • Do not describe advanced RAG as one specific method: It is the survey's umbrella term for a class of improvements, covering many techniques before and after retrieval.
  • Do not blame every failure on the retriever: Many failures happen at the query stage (the question itself is unsuitable for retrieval) or the context stage (the right content was retrieved but not used well).
  • Do not say that naive RAG is no longer useful: For simple factual lookups it is often the most cost-effective option, and advanced techniques should be added only as needed.

2.2 What query-side optimization techniques are there? ★★

One-sentence answer

The user's question is often not a good retrieval query, and query-side optimization fixes it before retrieval: query rewriting turns a question from a multi-turn conversation into one that can be retrieved on its own; HyDE first has an LLM write a hypothetical answer document and retrieves with it, turning "question finds answer" into "document finds document"; query decomposition splits a compound question into sub-questions that are retrieved separately; multi-query retrieves with several phrasings of the same question and fuses the results to raise recall. These techniques can be stacked, but each step adds an LLM call and a risk of error.

I will address three aspects: why the query should be optimized before retrieval, which problem each of the four main techniques solves, and their costs and trade-offs.

(1) The ceiling on retrieval quality is largely set by the query, and the user's question is naturally not a good retrieval query.

The user's question is written for people, not for a retriever. It may depend on the chat history ("And how much does it cost?"), contain small talk and irrelevant details, ask several things at once, or be worded very differently from the documents, which is the query–document asymmetry discussed in Chapter 1. The retriever can only match documents against the query itself, so if the query is flawed, no amount of reranking or generation quality downstream can make up for it. Therefore, "fixing" the query before retrieval is often the most cost-effective improvement.

(2) Each of the four main techniques targets one class of problems.

  • Query rewriting solves "the question cannot be retrieved on its own": The most necessary rewrite turns a question from a multi-turn conversation into a standalone question. For example, a user first asks "What is the battery capacity of the iPhone 16 Pro?" and then "And how much does it cost?"; searched on its own, the second question has no idea what "it" refers to. Giving the chat history and the current question to an LLM lets it rewrite the question as "What is the price of the iPhone 16 Pro?". In conversational products this step is practically mandatory. Rewriting can also drop small talk, fix typos, expand abbreviations ("k8s" → "Kubernetes") and add key terms to help BM25 match.
  • HyDE solves "the question and the answer look nothing alike": HyDE (Gao et al. 2022) does not retrieve first; instead, it has an LLM write a hypothetical answer document for the question, encodes this fake document into a vector, and retrieves from the real corpus with it. A question and its answer differ greatly in form, but a passage that "looks like an answer" is close to real answer documents in wording and terminology, so retrieval becomes "document finds document" instead of "question finds answer". Factual errors in the fake document matter little, because when the encoder compresses a passage into one vector it mainly keeps the topic and terminology, and a wrong number barely changes the vector.
  • Query decomposition solves "one question contains several sub-questions": For comparison questions ("Which phone has longer battery life, A or B?"), multi-aspect questions ("What are the definition, advantages and limits of RAG?") and multi-hop questions, encoding the whole question into one vector gives a blend of the sub-questions' meanings, and the top-k often covers only part of it, for example only documents about phone A. Decomposition has an LLM first split the question into simple sub-questions, retrieve for each, and then combine the results into an answer. Independent sub-questions can be retrieved in parallel; when a later sub-question depends on an earlier answer, they must be handled sequentially, which is in fact the iterative retrieval of 3.3.
  • Multi-query solves "retrieval is sensitive to wording": The same meaning phrased differently can retrieve very different neighbors with embeddings, and we do not know in advance which phrasing the document authors used. Multi-query has an LLM rewrite the question in 3 to 5 phrasings, retrieves for each, and fuses the results with RRF (see Chapter 1), a combination sometimes called RAG-Fusion. Each phrasing covers a different neighborhood in vector space, so together they give higher recall. It differs from decomposition in that multi-query uses different wordings of the same question, whereas decomposition uses different sub-questions.

(3) These techniques can be stacked, but every step has a cost, so they should be applied selectively by question type.

Each technique needs an extra LLM call, usually adding a few hundred milliseconds of latency, and HyDE must generate a whole passage, which costs more. Rewriting also carries a risk of intent drift: the model may misread the question or slip in assumptions, for example rewriting "the latest version" as a version number it believes is the latest but is actually outdated, so a common safeguard is to retrieve with both the original and the rewritten question and merge the results. Decomposition may split the question wrongly or miss a key sub-question; multi-query brings more candidates but also more noise, and usually needs to be paired with a reranker. A sensible approach is therefore to first rewrite conversational questions into standalone ones, then apply decomposition or multi-query only to complex questions, and verify with retrieval metrics on your own data that each step actually helps.

In summary: the essence of query-side optimization is translating "a question written for people" into "a query that makes it easy for the retriever to find the right documents"; different techniques address different flaws and should be chosen by question type.

Comparing query-side techniques:

Technique Problem it targets Extra cost Main risk
Query rewriting Questions that depend on the chat history, are vague or noisy One short LLM call Intent drift, injected assumptions
HyDE Query–document asymmetry; no labeled data for the retriever One longer LLM generation Off-topic fake documents in unfamiliar domains; amplified model biases
Decomposition Comparison, multi-aspect and multi-hop questions One LLM call + one retrieval per sub-question + one synthesis Bad splits, missing sub-questions
Multi-query Sensitivity to wording; low recall One LLM call + N retrievals More noise; variants drift from the original meaning
Filter extraction Hard constraints (dates, versions, regions) that embeddings cannot enforce One short LLM call A wrong filter removes the right answer

Going deeper: HyDE's formula, trainable rewriters and related prompting methods

(1) HyDE's search vector is the average of several fake documents and the original question.

\[ \hat{\mathbf{v}}_q = \frac{1}{N + 1}\left[\sum_{k=1}^{N} f(\hat{d}_k) + f(q)\right], \qquad \hat{d}_k \sim \mathrm{LLM}(\cdot \mid \text{instruction}, q) \]

Here \(q\) is the original question, \(\hat{d}_1, \dots, \hat{d}_N\) are \(N\) hypothetical documents sampled from the LLM given an instruction, \(f\) is the encoder, and \(\hat{\mathbf{v}}_q\) is the final vector used for retrieval. The original paper used InstructGPT to generate the fake documents and the fully unsupervised Contriever as the encoder; it explains "wrong details in the fake document get filtered out" as the encoder's dense bottleneck. Across tasks such as web search, QA and fact verification, and across several languages, HyDE clearly outperforms Contriever alone and is comparable to fine-tuned retrievers. The related Query2doc (Wang et al. 2023) concatenates the generated pseudo-document with the original question as the new query, which also expands the vocabulary for sparse retrieval such as BM25.

(2) The rewriter can be trained on downstream answer quality.

Rewrite-Retrieve-Read (Ma et al. 2023) uses a small model as the rewriter, warms it up with supervised data, and then trains it with reinforcement learning, where the reward is whether the downstream LLM answers correctly after reading the retrieved results. The motivation is that a query people consider "well written" is not necessarily the one that makes it easiest for the retriever to find the right documents.

(3) Two related prompting methods.

  • Step-back prompting (Zheng et al. 2023): For a very specific question, the model first poses a more abstract "step back" question, for example turning "What is the pressure of an ideal gas if its temperature doubles and its volume halves?" into "What is the ideal gas law?", retrieves the underlying principles with it, and then answers the original question.
  • Prompting methods for sequential decomposition: Least-to-most prompting (Zhou et al. 2022) and Self-Ask (Press et al. 2022) both "answer the easy sub-question first, then use its answer to move on", in the same spirit as the iterative retrieval of 3.3.

Follow-up questions

Follow-up 1: In multi-turn conversational RAG, what processing is needed before retrieval?

The current question must be rewritten as a standalone question that does not depend on the context. Questions in a multi-turn conversation often contain pronouns and ellipsis, such as "And how much does it cost?", and retrieving with them on their own is bound to fail. The approach is to give the chat history and the current question to an LLM and have it resolve the references and ellipsis, outputting a question that can be retrieved on its own. In conversational RAG products this step is practically mandatory.

Follow-up 2: What are the risks of query rewriting, and how can they be mitigated?

The main risks are intent drift and injected assumptions. The model may misread the question or write its own outdated knowledge into the query, for example rewriting "the latest version" as a specific but outdated version number. Mitigations include instructing the model in the rewriting prompt not to add facts absent from the original question, retrieving with both the original and the rewritten question and merging the results, and comparing retrieval metrics before and after rewriting on an evaluation set.

Follow-up 3: When does HyDE fail?

When the LLM does not know roughly what the answer looks like. For a company's internal systems or newly coined terms, the fake document the LLM writes may be completely off-topic and steer retrieval the wrong way; if the LLM holds a common misconception about a question, the fake document will follow the misconception, and the retrieved documents are more likely to support it. In addition, it does not help with exact-match lookups such as IDs and model numbers, and the latency of generating a long passage sits directly on the critical path of every query; the stronger the retriever already is, for example after supervised training in the relevant domain, the smaller HyDE's gain.

Follow-up 4: Why does multi-query improve recall?

Because different phrasings cover different neighborhoods in vector space. Embeddings are quite sensitive to wording, so a single phrasing only finds documents worded like it; merging the results of several phrasings naturally raises recall. With RRF fusion, documents retrieved by several phrasings rise in the ranking, which makes the result more robust. The cost is N times the retrievals (retrieval itself is cheap and can run in parallel; the main cost is the LLM call that writes the phrasings) and more noise among the candidates, so it is usually paired with a reranker.

Follow-up 5: How should retrieval handle hard constraints such as dates or versions in the user's question?

Extract the hard constraints from the question and hand them to metadata filtering, not to semantic retrieval. "2023" and "2021" sit very close together in vector space, and embeddings cannot tell them apart, so the results may well be 2021 financial reports. A practical approach (sometimes called self-query) has an LLM split the question into a semantic query ("financial reports mentioning layoffs") and a structured filter (year >= 2023), filters exactly on the condition first, and then runs semantic retrieval over the remaining documents. The risk is that a wrongly extracted condition (a misspelled field name, "last year" converted to the wrong year) directly filters out the right answer, so the extracted fields and values should be validated, and retrieval should fall back to no filtering when too few results remain.

Common mistakes

  • Do not say that HyDE requires the fake document to be factually correct: It only needs the fake document to resemble an answer in topic and wording; wrong details have little effect after encoding.
  • Do not conflate multi-query with query decomposition: The former uses several phrasings of the same question, the latter different sub-questions.
  • Do not say that query rewriting just fixes typos: Its most important use is resolving references in multi-turn conversations so the question can be retrieved on its own.
  • Do not stack every query-side technique indiscriminately: Each step adds latency and a chance to go wrong, so choose them by question type and verify them with metrics.

2.3 How do you retrieve for multi-hop questions? ★★

One-sentence answer

A multi-hop question requires chaining several facts, and the "bridge entity" to look up in the next hop is only known after reading the documents from the previous hop; it does not appear in the original question, so a single retrieval rarely finds everything. The solution is iterative retrieval: retrieve, generate, build a new query from what was generated, and retrieve again; IRCoT interleaves retrieval with chain-of-thought, retrieving with each reasoning sentence as soon as it is written, so reasoning guides retrieval and retrieval constrains reasoning. The costs are high latency and errors that propagate along the chain, so it should be used only for questions that genuinely need several steps.

I will address four aspects: why a single retrieval is not enough, the basic idea of iterative retrieval, how IRCoT works, and its costs and scope.

(1) The difficulty of multi-hop questions is that the bridge entity connecting the hops is not in the original question.

Many questions can only be answered by chaining several facts; these are called multi-hop questions. For example, "Where was the director of Inception born?" requires first finding that the director is Christopher Nolan and then finding that Nolan was born in London. The difficulty is that the document needed for the later hop ("Nolan was born in London…") has almost nothing in common with the original question: the word "Nolan" never appears in it, so retrieving with the original question is unlikely to rank that document near the top. "Nolan", which links the two hops, is called the bridge entity, and it only appears after reading the documents from the earlier hop. Retrieval for multi-hop questions must therefore happen over several rounds, with each round's query built from what has been read so far. Datasets such as HotpotQA (Yang et al. 2018), 2WikiMultihopQA (Ho et al. 2020) and MuSiQue (Trivedi et al. 2021) are designed specifically to test this ability.

(2) The core of iterative retrieval is building the next query from newly generated information.

The basic loop of iterative retrieval is: retrieve, generate, build a new query from what was generated, retrieve again, and so on. It works because the generated text contains information that was unknown before retrieval, such as the bridge entity, and using it as the next query finds documents that the original question could not. Methods differ in what is generated each round and what is used as the query. For example, Iter-RetGen (Shao et al. 2023) generates a complete answer in every round and uses "the original question + this round's answer" as the next query: even an imperfect answer mentions relevant entities and terms that help the next retrieval, and better retrieval in turn helps generate a better answer, so the two reinforce each other.

(3) IRCoT interleaves retrieval with chain-of-thought sentence by sentence, so reasoning and retrieval reinforce each other.

IRCoT (Interleaving Retrieval with Chain-of-Thought, Trivedi et al. 2022) is finer-grained. It first retrieves \(K\) paragraphs with the original question and then enters a loop: the LLM reads the question, all paragraphs collected so far and the reasoning written so far, and generates only the next sentence of reasoning; that sentence is then used as a query to retrieve \(K\) new paragraphs, which are added to the set; this continues until a sentence contains "the answer is…" or the step limit is reached. The whole process relies only on prompting and needs no extra training. The benefit of this interleaving runs both ways:

  • Reasoning guides retrieval: When the model writes "The director of Inception is Christopher Nolan", the bridge entity appears, and retrieving with that sentence naturally finds Nolan's birthplace.
  • Retrieval constrains reasoning: Each reasoning step sees newly retrieved facts instead of making things up from memory, so factual errors (hallucinations) in the chain of thought drop noticeably.

(4) The costs of iterative retrieval are high latency and error propagation, so it should be used only for questions that genuinely need several steps.

Every reasoning sentence costs an LLM call plus a retrieval, so latency is several times that of single-shot RAG. More dangerous is error propagation: if one reasoning sentence is wrong, for example naming the wrong director, it retrieves wrong documents, and later reasoning drifts further and further on a wrong foundation. When to stop also relies on heuristics that are not always reliable, and the context grows as paragraphs keep being added, so a cap is needed. On simple questions, all of this overhead is pure waste. In practice, therefore, one usually first decides whether a question needs multi-step retrieval at all, as Adaptive-RAG does by choosing among no retrieval, single-step retrieval and multi-step retrieval according to question complexity, or retrieves only when the model is uncertain, as FLARE does (both in Chapter 3). Going one step further and letting the model decide at each step whether to search, read or answer, and training that ability with reinforcement learning, leads to the agentic RAG of Chapter 5.

In summary: the key to multi-hop retrieval is letting the retrieval query update as reasoning progresses, using the bridge entities that emerge during reasoning to find documents the original question cannot.

Going deeper: IRCoT's procedure, its results and two other approaches

(1) IRCoT's procedure.

P ← Retrieve(q, K)                          # initial retrieval with the question
CoT ← []
repeat:
    s ← LLM(q, P, CoT)                      # generate the next reasoning sentence
    CoT.append(s)
    if "answer is" in s or steps ≥ max: break
    P ← P ∪ Retrieve(s, K)                  # use the new sentence as the next query
answer ← extract from CoT (or a reader reads q and P)

Here \(q\) is the original question, \(P\) is the accumulated set of paragraphs, and \(K\) is the number of paragraphs per retrieval. The final answer can be taken directly from the reasoning, or a reader can answer from all the collected paragraphs.

(2) Results.

On four datasets, HotpotQA, 2WikiMultihopQA, MuSiQue and IIRC, the paper reports that with GPT-3, retrieval improves by up to about 21 points and QA by up to about 15 points; similar gains hold in out-of-distribution settings and with small models such as Flan-T5, without extra training.

(3) Two other approaches.

  • Specially trained multi-hop dense retrieval: MDR (Xiong et al. 2020) concatenates the question with the passage retrieved in the previous hop as the query for the next hop, and trains the retriever specifically for this.
  • Building connections into the index in advance: HippoRAG (Gutiérrez et al. 2024) links the entities in the corpus into a graph at indexing time and, at query time, runs Personalized PageRank on the graph starting from the entities in the question, replacing several rounds of retrieval with a single propagation over the graph (see 2.4).

Follow-up questions

Follow-up 1: Why does retrieving with generated text find documents that the original question cannot?

Because the generated text contains bridge information that the original question lacks. The original question only describes what is being sought and does not contain the intermediate entities; while reasoning or answering, the model writes out these entities and related terms using the documents it has read and its own knowledge. These new words are closer, both lexically and semantically, to the documents for the later hop, so the retriever can find them.

Follow-up 2: How does IRCoT differ from Iter-RetGen?

They differ in what is used as the query each round. Iter-RetGen generates a complete answer each round and uses "the original question + the answer" as the next query, usually with few rounds; IRCoT retrieves after every reasoning sentence, which is finer-grained and exploits newly appearing bridge entities sooner, but needs more calls.

Follow-up 3: When does iterative retrieval stop?

Usually by heuristic rules, which is one of its weaknesses. IRCoT stops when "the answer is…" appears in the reasoning or the step limit is reached. A rule that stops too early misses information, while one that stops too late wastes calls and brings in more noisy paragraphs. A more flexible approach is to let the model learn to decide whether to keep retrieving, as in Self-RAG in Chapter 3 or the search agents trained with reinforcement learning in Chapter 5.

Follow-up 4: How does iterative retrieval differ from agentic RAG?

The difference is who decides the control flow. In iterative retrieval the loop is designed by hand, and each step is fixed as "generate one sentence, retrieve once"; agentic RAG wraps retrieval as a tool and lets the model decide whether to search, what to search for, which document to read and when to answer, and this behavior can be trained end to end (see Chapter 5).

Common mistakes

  • Do not say that increasing top-k solves multi-hop questions: The document for the later hop has low similarity to the original question, so it may not make the cut even with a large \(k\), and a large \(k\) brings in a lot of noise.
  • Do not say that IRCoT requires extra training: It relies entirely on prompting, inserting retrieval into the generation of the chain of thought.
  • Do not ignore error propagation: If one reasoning step is wrong, it retrieves wrong documents, and later reasoning builds on the error.
  • Do not use iterative retrieval for every question: On single-hop questions it only multiplies latency and cost.

2.4 What is GraphRAG, and when is it a good fit? ★★

One-sentence answer

GraphRAG (Edge et al. 2024) uses an LLM at indexing time to extract entities and relationships from the corpus into a knowledge graph, runs the Leiden algorithm for hierarchical community detection, and precomputes a summary for every community; at query time, global questions are answered by map-reduce over the community summaries, and questions about specific entities by expanding along the graph from the relevant entities. It suits global questions that require generalizing over the whole corpus, such as "What are the main themes of these interviews?"; the costs are expensive indexing, difficult incremental updates and no advantage on specific fact lookups.

I will address four aspects: why ordinary RAG answers global questions poorly, how the GraphRAG index is built, how querying works, and its costs and suitable scenarios.

(1) Vector RAG is good at local questions but poor at global questions that require generalizing over the whole corpus.

Ordinary vector RAG is good at local questions, where the answer sits in one or two chunks, such as "What is this product's warranty period?". But for a question like "Across these hundreds of user interviews, what are people mainly complaining about?", it is almost helpless. Such questions are called global "sensemaking" questions: the answer is not in any single chunk but requires generalizing and aggregating over the entire corpus. The reason is that top-k retrieval returns the \(k\) chunks whose wording is most similar to the question, and for a question like "What are the main themes?", the chunks with similar wording are essentially a few random passages that can neither represent the corpus nor count "which kind of complaint comes up most". Putting the whole corpus into the context does not work either: millions of tokens often exceed the context window, and even when they fit, the model misses much of the content in the middle (see 2.5). This is therefore essentially a task of query-focused summarization over a large corpus.

(2) The indexing stage processes the entire corpus in advance into "an entity graph + hierarchical community summaries".

The core idea of GraphRAG is to turn the corpus into a hierarchical summary structure before any question arrives. It first splits the documents into chunks and then calls an LLM on each chunk to extract the entities, the relationships between them, and verifiable statements about the entities (claims), such as dates and events. Next, the same entity extracted from different chunks is merged into one node, relationships become edges, and a relationship seen multiple times gets a higher edge weight, so information about the same entity scattered across many documents is gathered in one place. Then the Leiden algorithm performs hierarchical community detection on the graph: it first splits the graph into a few large communities and then recursively splits each into smaller sub-communities; each community is a group of tightly connected entities and roughly corresponds to a theme in the corpus. Finally, an LLM writes a report-style summary for every community, starting from the lowest-level communities and proceeding bottom-up level by level, with summaries becoming more general toward the top.

(3) Querying comes in two modes: global search and local search.

  • Global search aggregates community summaries with map-reduce: First a community level is chosen. In the map step, the summaries of all communities at that level are shuffled and split into batches, and the LLM writes an intermediate answer to the question from each batch in parallel, along with a helpfulness score; in the reduce step, the helpful intermediate answers are sorted by score, as many as fit are put into the context, and they are combined into the final answer. It can answer global questions because the community summaries are query-independent and precomputed, so a "map" covering the whole corpus exists before any question is asked, and every part of the corpus enters the map step through some community; since communities roughly correspond to themes, the answer is naturally organized by theme and is therefore more comprehensive and more diverse. The community hierarchy also provides a cost–quality knob: top-level summaries are cheap but general, lower-level summaries detailed but expensive.
  • Local search expands along the graph from the relevant entities: For a question about a specific entity, such as "Which projects has Zhang San worked on, and with whom?", reading a whole level of community summaries is both expensive and not detailed enough. Local search first uses embeddings to find the few entities most related to the question, then collects along the graph their descriptions, their relationships and neighboring entities, the summaries of their communities, and the source text chunks they were extracted from, fills the context budget in order of importance, and hands this to the LLM. Vector retrieval can only find the few passages worded like the question, whereas a node in the graph has already gathered, at indexing time, the information scattered across dozens of documents, and can follow relationship edges to find collaborators.

(4) GraphRAG's cost is concentrated in indexing, so it only suits global questions and scenarios rich in cross-document connections.

Indexing cost is GraphRAG's biggest problem: every chunk needs an LLM call to extract entities and relationships, and every community needs another LLM call to write its summary, so compared with a vector index that runs an embedding model once, the cost is several orders of magnitude higher. Updates are also hard, because new documents change the graph's structure and community partition, often requiring community detection and summarization to be redone. Extraction quality is another hazard: the LLM may miss entities or invent relationships, and wrongly merging different entities with the same name, or failing to merge different names for the same entity, pollutes the whole graph. In addition, it has no advantage on specific fact lookups; for a specific number, vector RAG is cheaper and more direct. GraphRAG therefore suits questions that need global generalization or cross-document connections over a relatively fixed corpus, such as analyzing a set of interviews, reports or news articles; a complete system usually offers global search, local search and ordinary vector retrieval together and picks one according to the question type.

In summary: the core of GraphRAG is building a "hierarchical summary map" of the entire corpus before any question is asked, trading expensive indexing for the ability to answer global questions.

Comparing vector RAG and GraphRAG:

Vector RAG GraphRAG global search GraphRAG local search
Questions it is good at Fact lookups whose answer sits in a few passages Themes and trends that require generalizing over the whole corpus Questions centered on a specific entity that need cross-document aggregation
Retrieval unit Chunks similar to the question All community summaries at one level Relevant entities with their neighbors, relationships, community summaries and source text
Indexing cost Low (one embedding pass) High (per-chunk extraction + per-community summaries) Shares the same index as global search
Query cost Low High (reads a whole level of summaries); lower levels cost more Moderate
Incremental updates Easy Hard Hard

Going deeper: the paper's setup, results and follow-up work

(1) Indexing details.

In the paper, each chunk has 600 tokens, with 100-token overlaps between adjacent chunks. Extracted entities have a name, type and description; relationships have a source entity, a target entity, a description and a strength. In hierarchical community detection, each level is a complete partition of all nodes; leaf communities are summarized directly from the descriptions of their entities, relationships and claims, and for higher-level communities whose content will not fit, sub-community summaries replace the raw descriptions. In the map step of global search, the helpfulness score ranges from 0 to 100, and intermediate answers scoring 0 are discarded.

(2) Results.

On a podcast-transcript corpus of about 1 million tokens and a news corpus of about 0.7 million tokens, the paper used an LLM as a judge for head-to-head comparisons: global GraphRAG beat vector RAG on comprehensiveness with win rates of about 72% to 83% and on diversity with about 62% to 82%, while vector RAG won on directness, a control metric, since directness naturally trades off against comprehensiveness and diversity. Even using only the top-level community summaries, each query needed over 97% fewer tokens than map-reduce summarization over the source text, while still outperforming vector RAG. Note that these evaluations rely on an LLM judge and generated questions, and criteria such as "comprehensiveness" and "diversity" are themselves somewhat subjective.

(3) Follow-up work.

Method Idea
LightRAG (Guo et al. 2024) Combines graph retrieval with vector retrieval and supports incremental updates
LazyGraphRAG (Microsoft Research 2024) Does not precompute community summaries, deferring the expensive LLM summarization to query time, on demand; Microsoft reports indexing costs identical to vector RAG and about 0.1% of full GraphRAG
HippoRAG (Gutiérrez et al. 2024) Runs Personalized PageRank over an entity graph, starting from the entities in the question, for multi-hop retrieval
HippoRAG 2 (Gutiérrez et al. 2025) Adds passages to the graph as nodes, improving multi-hop association without hurting simple factual QA
RAPTOR (Sarthi et al. 2024) Builds no explicit entity graph but recursively clusters and summarizes chunks into a summary tree, relying on the same idea of hierarchical summaries

Follow-up questions

Follow-up 1: How do GraphRAG's global and local search differ, and which questions does each suit?

Global search targets the whole corpus, local search a specific entity. Global search reads all community summaries at one level and runs map-reduce, which suits generalization questions such as "What are the main themes?"; local search expands along the graph from the entities related to the question, collecting entities, relationships, community summaries and source text, which suits questions that need to aggregate information about one entity across documents, such as "Which projects has this person worked on?". Specific fact lookups can still be handled by ordinary vector retrieval.

Follow-up 2: Why are community summaries generated in advance at indexing time?

Because the summaries are query-independent, so generating them in advance lets every question reuse them. A global question must cover the whole corpus; if every query had to generalize from the source text, the cost would be proportional to the corpus size. With precomputed hierarchical summaries, a query only needs to read one level of summaries, which cuts the cost drastically. The price is that the cost moves to indexing, and everything must be recomputed when the corpus changes. LazyGraphRAG makes the opposite trade-off: no summarization in advance, with processing done on demand at query time.

Follow-up 3: When should GraphRAG not be used?

When the workload is mostly specific fact lookups, or the corpus is very large or frequently updated. For specific facts, vector RAG is cheaper and more direct; for a very large corpus, per-chunk LLM extraction is prohibitively expensive; for a frequently updated corpus, the graph and communities must be rebuilt again and again. In addition, if the entities and relationships in the domain are hard for an LLM to extract accurately, the errors pollute the whole graph.

Follow-up 4: GraphRAG and HippoRAG both use graphs. How do they differ?

They use the graph to solve different problems. GraphRAG uses the graph for community detection and hierarchical summaries, in order to answer global generalization questions; HippoRAG produces no community summaries but runs Personalized PageRank over the entity graph from the entities in the question to find passages closely associated with them, in order to accomplish multi-hop association in a single retrieval.

Common mistakes

  • Do not describe GraphRAG as "attaching a knowledge graph to RAG": Its key elements are a graph extracted from the corpus by an LLM, hierarchical communities, precomputed community summaries, and map-reduce for global search.
  • Do not say that GraphRAG beats vector RAG on every question: On directness and specific fact lookups, vector RAG is better and cheaper.
  • Do not underestimate the indexing cost: Per-chunk LLM extraction and per-community summarization make it several orders of magnitude more expensive than a vector index.
  • Do not say that GraphRAG's graph is built by hand: The graph is extracted automatically from the corpus by an LLM, and extraction errors directly affect the results.

2.5 How should retrieved results be post-processed? ★

One-sentence answer

Retrieved candidates should not be pasted into the prompt as they are; post-processing does three things between retrieval and generation: reranking and truncation with a reranker plus deduplication with methods such as MMR decide what to include; extractive, abstractive or token-level compression decides how much to include; and placing the most relevant content at both ends, following the lost-in-the-middle pattern, decides how to arrange it. The goal is to put the most useful information where the model can use it most easily, with fewer tokens.

I will address three aspects: what to include, how much to keep, and in what order to place it.

(1) Select first: rerank and truncate with a reranker, then deduplicate, to reduce noise and redundancy.

There are many retrieved candidates, with both duplicates and noise, and as Chapter 0 explained, noisy documents distract the model, while longer prompts cost more and take longer. So reranking usually comes first: a cross-encoder rescores the top 50 or 100 candidates and only the best few are kept (how this works is in Chapter 1). One can also set a score threshold and drop everything below it, preferring fewer documents over noisy ones; if every candidate falls below the threshold, that itself signals that "the knowledge base may not contain the answer". Next comes deduplication: the top-k often contains nearly identical chunks, such as overlaps from chunking, multiple versions of the same document, or the same passage reposted in several places, which take up valuable slots without adding new information. The classic approach is MMR (Maximal Marginal Relevance, Carbonell & Goldstein 1998), which greedily selects documents one at a time, each one relevant to the question but not too similar to those already selected:

\[ \mathrm{MMR} = \arg\max_{d \in C \setminus S} \Big[\lambda \cdot \mathrm{sim}(d, q) - (1 - \lambda) \max_{d' \in S} \mathrm{sim}(d, d')\Big] \]

Here \(C\) is the candidate set, \(S\) is the set already selected, the term before the minus sign inside the brackets is the relevance of document \(d\) to the question \(q\), the term after the minus sign is the maximum similarity between \(d\) and the selected documents, i.e. the redundancy, and \(\lambda\) balances the two; at \(\lambda = 1\) it reduces to ranking by relevance alone. For multi-aspect questions, diversity also improves coverage of the different aspects.

(2) Then compress: context compression shortens the context while keeping the useful information, and the methods fall into three groups.

Even in a relevant chunk, often only a sentence or two truly matter, and the rest is background or unrelated content. Compression gives shorter prompts, lower cost and latency, and less noise.

  • Extractive compression introduces no new errors, but its compression ratio is limited: It picks the sentences relevant to the question from the retrieved documents and drops the rest. RECOMP (Xu et al. 2023) trains an extractive compressor that learns to pick sentences "that help the language model answer correctly". Since every output sentence comes from the source, it introduces no new errors, but it may cut away context needed for understanding.
  • Abstractive compression achieves higher compression, but may hallucinate: A usually smaller model writes a question-focused summary of the retrieved documents. RECOMP provides this kind of compressor too, and when the documents are irrelevant to the question it can output an empty string, meaning "add no retrieved content this time". The cost is that the summarizer itself may hallucinate or drop details.
  • Token-level pruning deletes words by information content; the result does not read fluently, but a large model can still understand it: LLMLingua (Jiang et al. 2023) uses a small language model to estimate each token's information content: tokens the small model predicts easily (low perplexity) carry little information and can be deleted, while hard-to-predict tokens are kept. LongLLMLingua (Jiang et al. 2023) builds on this by making compression aware of the question itself and reordering documents to ease the lost-in-the-middle problem described below.

(3) Finally arrange: lost in the middle means that the order itself affects answer quality.

Lost in the middle (Liu et al. 2023) shows that in multi-document QA, accuracy is highest when the document containing the answer is placed at the beginning or the end and lowest when it is in the middle, a U-shaped curve, and sometimes placing it in the middle is even worse than giving no documents at all (the phenomenon itself is covered in Chapter 3 of the Model Architecture direction). It shows that the same set of chunks can yield answers of different quality depending on how they are arranged, so the order used when building the prompt also needs to be designed.

  • Put the most relevant at both ends: Following the ranks given by the reranker, place the top-ranked documents alternately at the beginning and the end, leaving the least relevant in the middle. The retrieval reordering proposed by Jin et al. (2024) follows this idea and needs no training.
  • Include fewer: Reranking and compression reduce the number of documents, which shortens "the middle" itself.
  • Put the question after the documents: This keeps the question right next to where the model starts generating; some setups place the question both before and after the documents.
  • Keep chunks from the same document in their original order: Arranging them by their original position rather than by relevance preserves the coherence of the narrative, and OP-RAG (Yu et al. 2024) found that this works better for long-document QA. Scattered fact lookups suit ordering by relevance, while questions that need the flow of the context suit the original order.
  • Mitigate through training: Fine-tune the model on data where the relevant information appears at random positions, so it learns to use the whole context evenly (see Chapter 6).

In summary: the goal of context post-processing is to put the most useful information where the model can use it most easily, with the fewest tokens: reranking and deduplication decide what to include, compression decides how much, and ordering decides how to arrange it.

Going deeper: the economics of compression, alternating placement by rank and other compression methods

(1) Compression only pays off when the time it saves exceeds the compressor's own cost.

The compressor itself must run a model: extractive and token-level methods need a small model to score all the text, and abstractive methods must also generate the summary token by token. Compression is worthwhile only when the prefill time it saves, together with the quality gain from less noise, outweighs this overhead. The LLMLingua paper reports compressing prompts by up to 20× on some tasks with little loss in performance; but the harder you compress, the greater the risk of losing key information.

(2) Alternating placement by rank.

If the reranker's ranks are 1, 2, 3, 4, 5, placing them alternately at the two ends gives the order 1, 3, 5, 4, 2: the highest rank at the beginning, the second highest at the end, and the lowest in the middle.

(3) The number of documents and answer quality form an inverted U.

OP-RAG observed that as the number of chunks grows, answer quality first rises and then falls: too few miss information, while too many bring in noise and worsen lost in the middle. The number of chunks therefore needs to be tuned on a validation set.

(4) Compressing documents into continuous vectors.

Another family of methods compresses documents into a few continuous vectors (soft tokens) that are fed directly into the model, for example ICAE (Ge et al. 2023) and xRAG (Cheng et al. 2024). They achieve the highest compression but require specially training the model or an adapter.

Follow-up questions

Follow-up 1: How does MMR balance relevance and diversity, and how should \(\lambda\) be chosen?

At every step MMR trades off "relevance to the question" against "redundancy with the documents already selected". A larger \(\lambda\) weights relevance more, and at \(\lambda = 1\) it reduces to ranking by relevance alone; a smaller \(\lambda\) weights diversity more. For corpora with many duplicate sources or for multi-aspect questions, \(\lambda\) can be lowered; for factual questions whose answer is in one place, relevance should be favored. In practice it is tuned on a validation set. The cost is that it may drop a useful chunk that merely resembles another relevant document.

Follow-up 2: Why is context compression riskier for multi-hop questions?

Because the key sentence that multi-hop reasoning needs may look completely unrelated to the original question. For example, if the question is "Where was the director of Inception born?", the key sentence "Nolan was born in London" shares no words with the question; compressing by relevance to the question can easily delete it, breaking the reasoning chain. In multi-hop settings, therefore, compression should be relaxed, or each step of iterative retrieval should compress with respect to the current sub-question.

Follow-up 3: Should retrieved documents be ordered by relevance or by their original order?

It depends on the task. Scattered fact lookups suit ordering by relevance, with the most relevant at both ends; long-document QA that requires following the narrative suits arranging chunks from the same document in their original order, and OP-RAG found that the latter works better for long-document QA.

Follow-up 4: Is it always better to give the model more documents?

No. More documents raise recall but also bring more noise, a stronger lost-in-the-middle effect and higher cost. OP-RAG observed that answer quality first rises and then falls with the number of chunks; Jin et al. (2024) also found that "seemingly relevant" distractors retrieved by strong retrievers are more harmful. The number of documents therefore needs to be tuned on a validation set.

Common mistakes

  • Do not say that more documents are always better: Noise and position effects make answer quality first rise and then fall.
  • Do not say that token-level compressed text must read fluently: It is meant for a large model, which can still understand it after low-information tokens are deleted.
  • Do not say that abstractive compression introduces no errors: The summarizer itself may hallucinate; only extractive methods guarantee that every output sentence comes from the source.
  • Do not assume that concatenating documents in descending score order after reranking is enough: Because of lost in the middle, a document's position in the prompt also affects answer quality.

2.6 Will long-context models replace RAG? ★★★

One-sentence answer

Not entirely; the two are complementary. Long context lets the model see everything, which suits synthesis and reasoning across documents, but every query pays the prefill cost and latency for the whole corpus, the corpus size is bounded by the window, and the effective length is limited, with lost in the middle and distraction problems; RAG is cheap, scales to massive and frequently updated corpora, and makes access control and precise citations easy, but its ceiling is limited by retrieval recall. In practice the two are often combined: use RAG first and fall back to long context when it cannot answer (as in Self-Route), or use a long-context model to read larger retrieval units; a small, stable corpus can simply be placed in the context together with prompt caching.

I will address four aspects: cost and latency, accuracy, the conclusions of empirical studies, and how to combine the two.

(1) Cost, latency and scale are long context's biggest weaknesses.

Prefill compute grows at least linearly with input length, and the attention part grows quadratically (prefill is covered in Chapter 0 of the Inference, Evaluation & Deployment direction). If every query reprocesses a 1-million-token corpus, while RAG processes only 5 chunks of about 500 tokens each, i.e. about 2,500 tokens, then long context processes about 400 times as many tokens per query as RAG, and both cost and time-to-first-token are several orders of magnitude higher. Prompt caching can reuse the KV cache of an identical prefix, greatly reducing the prefill cost when the same corpus is queried repeatedly, but it requires the prefix to match token by token, and the KV cache for a million tokens itself occupies a great deal of GPU memory (see Chapter 1 of the Inference, Evaluation & Deployment direction). Moreover, the corpus size is bounded by the context window, typically on the order of \(10^5\) to \(10^6\) tokens, whereas an enterprise knowledge base or web search covers millions of documents, which simply cannot fit.

(2) On accuracy, each wins in some cases.

  • Long context's strength is synthesis and cross-document reasoning: The model sees everything, which suits questions that require synthesizing an entire document or reasoning across several documents, whereas RAG's chunking and retrieval would fragment such information.
  • Long context's weakness is a limited effective length and susceptibility to distraction: There is often a gap between the length a model claims to support and the length it can actually use effectively, and lost in the middle still applies (long-context evaluation is covered in Chapter 3 of the Model Architecture direction); the more seemingly relevant distractors the context holds, the more easily the model is led astray (Jin et al. 2024).
  • RAG's ceiling is set by retrieval recall: If retrieval misses, the answer is bound to be wrong; but for questions that look up specific facts in a massive corpus, RAG has already filtered out the vast majority of irrelevant content and has less noise, although distractors that resemble the answer can still get in.

(3) Empirical results are not one-sided; the best choice depends on the model, the length and the task.

Xu et al. (2023) found that a 4K-context LLM with simple retrieval matched a fine-tuned model extended to a 16K context on long-context tasks, with far less compute, and that retrieval also helped models whose context had already been extended. Li et al. (2024) found, with the strongest long-context models of the time, that given enough resources, long context consistently beat RAG on average, but RAG cost far less. OP-RAG (Yu et al. 2024), on the other hand, found that with the right number of chunks, RAG could reach higher answer quality than feeding in the whole document, with far fewer tokens. The more systematic LaRA benchmark (Li et al. 2025) compared the two across 11 models and concluded that neither is a silver bullet: the best choice depends on the interplay of model capability, context length, task type and retrieval quality. Whether long context will replace RAG is therefore not a question with a single answer; it has to be answered scenario by scenario.

(4) In practice the best approach is often to combine the two.

  • Routing: RAG first, long context when RAG cannot answer: Self-Route (Li et al. 2024) starts from the observation that for most questions, RAG and long context give exactly the same answer, so there is no need to pay for long context every time. It first gives the model the question and the top-k retrieved chunks and allows it to output "unanswerable" when it cannot answer; only for questions judged unanswerable is the full long context given to the model to answer again.
  • Use the long-context model as a stronger reader: Since the model can read longer inputs, retrieval does not have to return only a few small chunks; it can return larger units, such as whole sections or documents. LongRAG (Jiang et al. 2024) groups related documents into retrieval units of about 4K tokens, so the retriever only needs to find a few units and the long-context reader handles the rest, which both lightens the retriever's burden and reduces the fragmentation caused by chunking.
  • Choose by scenario: When the corpus is small, fixed and queried repeatedly (a contract, a product manual, a medium-sized codebase), put it straight into the context with prompt caching, which is simple and accurate; when the corpus is large, changes often, or requires access control or precise citations (an enterprise knowledge base, web search), use RAG; for questions that need global synthesis, long context or GraphRAG fits better; for specific fact lookups, RAG is cheaper and more precise.

In summary: long context strengthens the "reader" in RAG but does not remove the need to "first select the relevant content from a massive corpus"; corpus size, update frequency and cost constraints determine which one to use, and most production systems combine the two.

Comparing long context and RAG:

Long context (everything in the prompt) RAG
Cost per query Grows with corpus size; every query prefills the whole corpus (prompt caching helps when the same corpus is reused) Only \(k\) chunks; roughly constant
Latency Long prefill, high time-to-first-token Retrieval adds tens of milliseconds; short prompt
Corpus size Bounded by the context window (about \(10^5\)–\(10^6\) tokens) Practically unbounded (millions of documents)
Accuracy Sees everything; strong at synthesis and cross-document reasoning, but degrades with length and position Capped by retrieval recall, so a miss means a wrong answer; strong at specific fact lookups
Noise Everything irrelevant is in the context too Retrieval and reranking filter out most noise, though similar distractors still get in
Updates Just send the new documents Re-index the changed documents
Access control and citations Hard to enforce per user; coarse citations Filter by permission at retrieval time; chunk-level citations
Engineering complexity Simple, no pipeline Chunking, embeddings, index and reranker to maintain

Going deeper: Self-Route's details, cache-augmented generation and recent evidence

(1) Self-Route's setup and results.

The paper observes that for about 63% of questions, RAG and long context give exactly the same answer. The RAG step uses \(k = 5\) retrieved chunks by default, and the prompt says "if the query cannot be answered from this text, output unanswerable"; the "can I answer?" judgment is generated in the same call as the answer, so the routing itself adds almost no cost. Most questions are settled at the RAG step, cutting computation cost by about 39% (GPT-4o) to 65% (Gemini-1.5-Pro), with average quality close to using long context for everything. It relies on the model recognizing fairly accurately that "I cannot answer this"; if the model answers anyway from irrelevant chunks, questions that should have been escalated stay at the RAG step, which is the same calibration problem discussed in Chapter 3.

(2) Cache-augmented generation (CAG).

When the knowledge base is small enough to fit entirely in the context, there is an even more thorough option: Cache-Augmented Generation (CAG, Chan et al. 2024). At deployment time it feeds all the documents to the model once, computes the corresponding KV cache and saves it; after that, each question is simply appended to this KV cache and generation continues, with no retrieval step at all. It has no retrieval latency, no missed retrievals, and a much simpler system with no chunking, embeddings or index to maintain; the documents are prefilled only once, after which each question mainly costs reading the cache and generating the answer. The costs are that the knowledge base must fit in the context window, the KV cache itself occupies a lot of GPU memory or storage, the cache must be recomputed whenever the documents change, and the position effects and distraction problems of long context still apply. CAG therefore suits small, stable knowledge bases, such as a product manual or a fixed set of regulations.

(3) Recent evidence: windows keep growing, but "fits" does not mean "used well".

The context windows of mainstream models have reached the million-token scale; for example, GPT-4.1 supports 1M tokens, and Llama 4 Scout claims to support 10M tokens. However, Chroma's technical report (Hong et al. 2025) tested 18 models and found that even on simple tasks, performance keeps degrading as the input grows: the lower the semantic similarity between the question and the key information, the faster the decline; adding even a single topically related distractor reduces accuracy; and on LongMemEval, giving only about 300 tokens of relevant content worked better than giving the full conversation history of about 113K tokens. This shows that retrieving first and then handing the model a small amount of selected content remains valuable in the era of long windows.

Follow-up questions

Follow-up 1: Context windows have reached a million tokens. Is RAG still necessary?

Yes, because of scale, cost, updates and permissions. Enterprise knowledge bases and the web are far larger than any context window; even when the corpus fits, paying the prefill cost for the whole corpus on every query is impractical; when knowledge changes often, RAG only needs to re-index the changed documents; and per-user permission filtering and chunk-level citations are easy to implement only at the retrieval stage. Long context changes "how much can be read after retrieval", not "whether retrieval is needed first".

Follow-up 2: How does Self-Route route between RAG and long context, and what does it rely on?

It is a cascade from cheap to expensive. The model first reads only the top-k retrieved chunks and is allowed to answer "unanswerable"; only the questions it cannot answer are escalated to the full long context. The routing judgment is generated in the same call as the answer, so there is almost no extra cost. It relies on the model accurately recognizing when it cannot answer; if the model answers anyway when the information is insufficient, it misses questions that should have been escalated.

Follow-up 3: Can prompt caching eliminate the cost problem of long context?

It can only partially mitigate it. It saves only the prefill of an identical prefix, requires the prefix to match token by token, and is invalidated as soon as the corpus changes; the KV cache for a million tokens takes a lot of GPU memory and competes with other requests for space; and during decoding, every generated token still attends over the entire long context. It suits scenarios where "the same fixed corpus is queried repeatedly", not large, changing knowledge bases.

Follow-up 4: What is CAG, and which scenarios suit it versus RAG?

CAG precomputes the whole knowledge base into a KV cache and generates directly after it at query time, skipping retrieval entirely. It suits small, stable knowledge bases that are queried repeatedly, such as a product manual or a fixed set of regulations; once the knowledge base grows large or changes frequently, the storage and recomputation costs of the KV cache become too high, and RAG is the better choice again.

Common mistakes

  • Do not say that long context sees everything and is therefore always more accurate than RAG: Limited effective length, lost in the middle and distractors all make quality degrade with length.
  • Do not say that RAG is merely a stopgap from the era of small context windows: The needs for scale, cost control, updates and access control do not disappear as windows grow.
  • Do not say that prompt caching makes long context as cheap as RAG: It saves prefill only when the prefix is identical, and the GPU memory of the KV cache and the attention cost during decoding remain.
  • Do not treat the two as an either-or choice: Routing, long-context readers and choosing by scenario are all ways of combining them.

2.7 How do you do RAG over structured data such as tables and databases? ★

One-sentence answer

Tables and databases do not fit the standard "chunk, embed, top-k" pipeline: chunking breaks tables, numbers carry a weak semantic signal for embeddings, and questions over tables often need computation over all rows. For tables, preserve the structure during parsing and repeat the header in every chunk, or retrieve on a textual description of the table and hand the original table to the generator; when the data lives in a database, use text-to-SQL so the model generates a query and computes exactly over all the data; when knowledge is spread across several data sources, put a router at the front.

I will address four aspects: the problems tables cause, how to handle tables, text-to-SQL, and routing across data sources.

(1) Tables run into three problems in the standard RAG pipeline.

  • Chunking breaks tables: When chunking by length, a table is split into several pieces, and the later pieces lose the header, so there is no way to know what a "128" in some column means.
  • Tables embed poorly: Rows of numbers carry almost no semantic signal, so for "Which product is the most expensive?", the chunks worded similarly are usually prose paragraphs rather than the price list.
  • Questions over tables often need computation: Sums, comparisons, sorting and filtering all require seeing every row of the table, while top-k only returns a few pieces.

(2) The key to handling tables is preserving their structure and separating "the representation used for retrieval" from "the content given to the generator".

During parsing, the table structure should be preserved as completely as possible by converting it to Markdown or HTML; a small table becomes a single chunk, while a large table is split by rows with the header repeated in every chunk. To make embeddings match more easily, each row can be serialized into a sentence, such as "Product A's revenue in Q1 2024 was 120 million yuan". A more general approach is multi-representation indexing: have an LLM write a description of the table, stating what the table is about, which columns it has and what period it covers, retrieve on the description, and once it is hit, hand the original table to the generator. When a table is large and the question needs computation, a better approach is to load the table into a database or a DataFrame and have the model write SQL or code to compute the answer, rather than doing "mental arithmetic" in the prompt.

(3) When the data lives in a relational database, the most fitting "retrieval" is a SQL query.

The text-to-SQL flow is: give the LLM the database schema (table names, column names, types, a few sample rows and descriptions of what the columns mean) together with the user's question and have it generate SQL; execute the SQL, then give the results back to the LLM to answer in natural language. Compared with vector RAG, it can perform exact aggregation, filtering and joins over all the data, for example "the three products with the highest return rate in East China last month", something that can never be computed from the top-k text chunks. Its main difficulties are three:

  • Schema linking: An enterprise database may have hundreds of tables and thousands of columns that cannot all fit in the prompt, so the tables and columns relevant to the question must be found first. This step is itself a retrieval problem: index the table and column descriptions as well as past example queries, retrieve first, and then generate SQL.
  • Ambiguity in business meaning: Terms such as "active users" or "revenue" may be defined differently by different departments, so the metric definitions need to be written down and provided to the model.
  • Silent errors: The SQL runs but the logic is wrong, for example a missing filter or a join on the wrong table, and the result looks reasonable but is actually incorrect.

(4) When knowledge is spread across several data sources, a router dispatches each question to the right source.

In real systems, knowledge is often spread across several kinds of sources: unstructured documents suit vector or hybrid retrieval, structured business data suits SQL, and knowledge graphs with explicit entity relations suit graph query languages such as Cypher or SPARQL. Many systems therefore put a router at the front, using rules or an LLM classifier to decide which source or sources a question should go to: "What is the return policy?" goes to the document store, "How many orders were returned last month?" goes to the database, and a question involving both queries both and merges the results into one answer. If routing is wrong, everything after it is wrong, so the router itself needs to be evaluated separately. Wrapping each data source as a tool and letting the model decide in a loop which one to call leads naturally to the agentic RAG of Chapter 5.

In summary: the key to RAG over structured data is handing each kind of data to the tool best suited to it: semantic retrieval for text, preserved structure and separate retrieval representations for tables, and SQL or code for exact computation.

Going deeper: text-to-SQL benchmarks and engineering details

(1) Benchmarks are getting closer to real enterprise settings.

Benchmark Characteristics
Spider (Yu et al. 2018) The classic cross-database benchmark, with small schemas and clean data
BIRD (Li et al. 2023) Larger databases and "dirtier" data, requiring external knowledge to understand what values mean
Spider 2.0 (Lei et al. 2024) Tasks from real enterprise workflows, with large databases, several SQL dialects and multi-step operations; at release, o1-preview solved only about a fifth of the tasks, compared with over 90% on Spider 1.0 and about 73% on BIRD

(2) Engineering practices that reduce silent errors.

Common practices include showing the generated SQL to the user for checking; feeding execution errors back to the model for self-correction; validating the results of important queries, for example checking whether the number of returned rows and the value ranges are reasonable; and comparing execution results rather than just SQL strings during evaluation.

Follow-up questions

Follow-up 1: When should you use text-to-SQL instead of vector retrieval?

When the data is structured and the question needs exact aggregation, filtering or joins. For example, "the average order value per region last month" must be computed over all rows; vector retrieval only returns a few fragments and is bound to get it wrong. Conversely, if the question is about unstructured text such as policies or descriptions, vector retrieval is more suitable. When both kinds of questions occur, use a router to dispatch them.

Follow-up 2: The generated SQL runs, but the result is wrong. How do you detect and mitigate this?

This is the most dangerous error in text-to-SQL, because the result looks perfectly reasonable. Mitigations include showing the SQL to the user for checking; providing clear column descriptions and metric definitions to reduce semantic misunderstandings; sanity-checking the results of important queries; and letting the model self-correct based on error messages when execution fails.

Follow-up 3: What security issues does a text-to-SQL system have?

Mainly unauthorized access, destructive operations and resource abuse. Use only read-only accounts, enforce row-level permissions per user, limit query size and execution time, and guard against users injecting malicious SQL through their questions.

Common mistakes

  • Do not chunk tables by length as if they were ordinary text: The header is lost, and the resulting table fragments cannot be understood correctly.
  • Do not let the LLM perform aggregate computations over a large table inside the prompt: Hand them to SQL or code instead.
  • Do not say that a SQL query that runs must give the right answer: Logically wrong SQL runs just as well and returns plausible-looking results.
  • Do not put the entire schema of a large database into the prompt at once: Do schema linking first and provide only the relevant tables and columns.