GraphRAG and structured retrieval

Questions a top-k of chunks cannot answer (chains of entities, the whole corpus, counts over every row): knowledge graphs extracted by language models, entity resolution, Leiden communities, Microsoft GraphRAG's global, local and DRIFT search, cheaper graphs (LazyGraphRAG, LightRAG, HippoRAG), then text-to-SQL, tables and Cypher. Measured on the topic's HotpotQA and on Spider databases on an Apple M1 Pro, small-scale and labelled; published results kept apart. A child of Topic: rag-and-retrieval. Data as of October 2026. Reading: 40 min, plus 21 in closed details.

The idea in one screen

A top-k of similar chunks answers only questions whose evidence looks like the question. When the evidence is a chain of entities, the whole corpus or every row of a table, you need structure: GraphRAG pays at index time to turn text into entities, edges and community summaries; structured retrieval writes a SQL or Cypher query against data that already has structure. Each pays off only when its links are real.

Fig. 1 sets four kinds of question beside the structure that answers each and when it is paid for. The examples are the topic's own: a HotpotQA bridge question (answer: Chief of Protocol) and a Spider question over the concert_singer database. The shapes are schematic (how many chunks, communities and beads is layout); the stages in sections 5, 6 and 7 run the real graphs. Highlighted: what this page builds.

  1. Four questions, four structures. Local, multi-hop, global and aggregate. The local column is the parent's pipeline, the baseline everything here must beat; the other three need structure that a list of chunks does not have.
  2. Local: top-k chunks. "What year was Goldfinger released?" The answer is in one passage that shares words or meaning with the question, so a search returns it among the top k. Index: embeddings. Query: 1 search, 1 call.
  3. Multi-hop: an entity graph. "What post did the actress who played Corliss Archer hold?" The answer needs a chain: passage A names an entity, passage B says something about it and may share nothing with the question. Here A (the film) names Shirley Temple, and B is about her. Walk from A through the shared entity to B. Index: 2 LLM calls per chunk, plus entity resolution. Query: a walk or PageRank, no LLM.
  4. Global: community summaries. "What are the main themes of these 10,000 reports?" The answer is a property of the whole collection, and any top 10 samples ten fragments. The graph's communities each get a report written in advance; map the question over every report, then reduce the useful points into one answer. Index: + 1 LLM call per community. Query: 1 call per community.
  5. Aggregate: SQL over every row. "How many singers are from France?" The answer is a count, sum, maximum or join over records; retrieval returns k rows, and the answer depends on all of them. Retrieve the schema, write the query, and the database reads every row of singer (6 rows here, millions in production). Index: none, the data is already tables. Query: 1 call, then the database counts.

You need: hybrid search, reciprocal rank fusion and self-query filters from The retrieval pipeline; the topic's running example (200 HotpotQA questions over 9,760 paragraphs, bge-small, Qwen3-1.7B and 4B) from Topic: rag-and-retrieval, whose shared runs (src/agent) include the ReAct agent this page compares against. The agent loop itself is Agentic retrieval, long context and memory's; temporal graphs as an agent's memory (Zep, Graphiti) are Context engineering's; graph and relational databases as products, and SQL itself, are Topic: databases's; judged answer quality is RAG and retrieval evaluation's.

Triple
one fact as (subject, relation, object): (Shirley Temple, played, Corliss Archer).
Entity resolution
deciding which mentions are the same thing ("Temple", "Shirley Temple Black").
Community
a set of nodes linked more densely to each other than to the rest; found by Leiden.
Community report
GraphRAG's LLM-written summary of one community, the unit global search reads.
Global, local, DRIFT
GraphRAG's query modes: map-reduce over reports, entity-centred context, and reports followed by local follow-ups.
Personalised PageRank
a random walk that keeps restarting at the question's entities; its visit rates rank the graph.
Schema linking
matching a question's words to the tables and columns a query needs.
Execution accuracy
a generated query counts as right when its result equals the gold query's result.
The page's findings in one table (reference: every headline number, with its section)
findingthe numbersection
A graph is paid for at index time, per chunkgraphrag 3.3.0 sends 1,717 tokens of instructions with every chunk, then a gleaning call; on 125-token paragraphs the first call alone is 14.0 times the text; LightRAG 1.5.7 sends 4,253 tokens per paragraph before the model writes a word measured3, 9
Entity resolution decides whether the graph connectsexact upper-cased names join 71 of 160 bridge pairs; looser matching up to 114, but only 16 of 30 hand-checked extra merges were right measured4
A graph helps multi-hop retrieval only when its links are realboth gold paragraphs in the top 5 of 200: dense 137, hybrid 143, PageRank over noun phrases 79, expansion along title links 169; answer F1 0.402 to 0.464 (paired 95% interval of the gain 0.015 to 0.110) at a third of the agent loop's prompt tokens measured8
Global questions are a map-reduce over community summariesjudged more comprehensive than top-k retrieval in 72 to 83% of comparisons on two 1 to 1.7 M-token corpora, at one model call per community per question published6
Cheaper graphs exist; read their claims carefullyto index 11,656 passages: GraphRAG 115.5 M input tokens, LightRAG 68.5 M, HippoRAG 2 9.2 M published7, 9
For counts and joins, use SQL48 of 100 Spider questions are aggregates and 23 read more than 10 rows; retrieving 5 tables puts every needed table in the prompt for 98 of 100 with 339 schema tokens instead of 5,637, and Qwen3-1.7B then writes correct SQL for 56 of 100, as with the right database given (56) and twice the full dump (27) measured10
How to read the numbers (labels, machine, what transfers)
measured = run on an Apple M1 Pro (16 GB, shared with other jobs) with the scripts in this page's src/scripts, on the topic's running example (its src/data/load.py) or the Spider 1.0 dev databases; every result here is small-scale (394 to 9,760 paragraphs, 100 SQL questions) and says so. published = a paper or benchmark run by its authors, dated; vendor = a company blog about its own product; derived = arithmetic on the above, formula shown; illustrative = a toy drawn to show a mechanism. What transfers to production: the counts, ratios and failure kinds; not the absolute seconds, and not the exact accuracies of a 1.7 B or 4 B model, which are far below the hosted models the published numbers use.

1. What a top-k of chunks cannot answer

Everything on the parent page assumes the answer lives in a few passages that resemble the question. That assumption fails in three of the four ways of Fig. 1: multi-hop, global and aggregate.

On the running example's 200 HotpotQA questions, one dense search (bge-small, the root agent runs' search tool) puts at least one gold paragraph in the top 10 for almost every question, but both for 164, and both in the top 5 for 137 measured: the second hop is what is missed. A graph attacks that: if paragraph A mentions an entity and paragraph B is about it, an edge joins them, and retrieval can walk from A to B without the question ever naming B.

Predict: 100 Spider questions over 20 real databases. How many are aggregates (COUNT, SUM, AVG, MIN, MAX or GROUP BY), and of those, how many depend on more than 10 rows?

When none of this matters. Most questions in most products are local. For those, hybrid search with a reranker is cheaper and at least as good as anything on this page; the GraphRAG paper evaluates only global questions, and Microsoft later built DRIFT search specifically for local ones (section 6).

2. Knowledge graphs, and the open graph GraphRAG builds

A knowledge graph stores facts as nodes (entities: a person, a film, a place) joined by edges (relations: starred in, held); one fact is a triple. Two families store them: property graphs (Neo4j, Kùzu, Memgraph, Amazon Neptune), where nodes and edges carry a label and key-value properties, queried with Cypher or its ISO successor GQL; and RDF stores (Wikidata, GraphDB, Apache Jena), where everything is a triple of URIs, queried with SPARQL, and the schema (an ontology) is itself data.

A schema (which node labels and relation types are allowed) separates a curated knowledge graph from what GraphRAG builds. GraphRAG extracts an open graph: whatever entities and relation phrases a language model finds in each chunk, guided only by a short list of entity types. Cheap to start, messy to use: the same entity under five spellings, relations that are free text ("was the third film in the series of"), no constraints to check against.

HotpotQA is a fair test bed because it was built from exactly such links: its authors took the hyperlink graph of the first paragraphs of English Wikipedia and wrote bridge questions over pairs of articles joined by a hyperlink, the linked article's subject being the bridge entity (Yang et al. 2018, section 2) published. Keep that in mind in section 8: a graph built from title mentions recovers the dataset's own construction.

The question names the film and the character, never the actress: one shared node makes the second hop
Kiss and Tell1945 film Shirley Templeperson: the bridge entity Chief of Protocolpost Corliss Archer starred held played paragraph A: the film paragraph B: the actress the question names the film and the character, never the actress

The root's example bridge question from HotpotQA's dev set, drawn by hand from its two gold paragraphs (answer: Chief of Protocol). Once "Shirley Temple" is a node shared by both paragraphs, a graph walk reaches paragraph B in one hop.

3. Building the graph: extraction with a language model, or without one

The concrete case. graphrag 3.3.0 (pip graphrag, released 2026-10-08, read at tag v3.3.0) cuts documents into chunks of 1,200 tokens with 100 of overlap (o200k_base tokens) and sends each chunk with one long prompt: 1,717 tokens of instructions and worked examples (1,734 Qwen3 tokens) measured (s_prompt_tokens.py). The model answers with records such as ("entity"<|>SHIRLEY TEMPLE<|>PERSON<|>...) and ("relationship"<|>source<|>target<|>description<|>strength), over four default entity types: organization, person, geo, event. Then comes gleaning: a second message tells the model "MANY entities and relationships were missed" and its answer is appended, so every chunk costs two calls and the second re-sends the first call's prompt, chunk and answer.

On the root agent runs' subset (the 10 paragraphs of each of the first 40 test questions, 394 paragraphs of median 125 Qwen3 tokens), the first call has a median prompt of 1,871 tokens: 53,062 tokens of text become 740,923 prompt tokens before gleaning, 14.0 times the text measured. With 1,200-token chunks each indexed token costs (1,717 + 1,200) / 1,200 = 2.4 prompt tokens derived, one reason graphrag uses big chunks; the GraphRAG paper measured what that costs in recall: with GPT-4 on a HotpotQA sample, 600-token chunks yielded almost twice as many entity references as 2,400-token chunks (Edge et al., appendix A.2) published.

Measured with the local model (graphrag's own prompt and parser, Qwen3-1.7B, the first 150 subset paragraphs): 4,368 prompt and 922 output tokens per paragraph over the two calls, 14.4 s of generation per paragraph measured. Three findings:

  • Prefix caching is worth most here. llama-server recomputed only 113,654 of the 655,264 prompt tokens (17%), because the 1,700 tokens of instructions are an identical prefix in every call; providers that discount cached input pass part of that on.
  • Gleaning did not glean. Records grew from 983 to 1,663, but distinct (name, type) pairs per paragraph only from 6.36 to 6.43: the model answered "MANY entities were missed" by repeating its first list (one answer opened with "I apologize for the confusion"). Qwen3-4B did the same. The second call doubled the cost and added almost nothing.
  • The entity types matter. With four types a film, a song or a sports season has nowhere to go: the graphrag prompt recovered the paragraph's own title for 82 of these 150 paragraphs against 99 for the root agent runs' untyped one-call prompt. Set the types for your corpus (graphrag prompt-tune, cli/main.py line 249).
The instructions dominate small chunks: drag the chunk size and watch the prompt per text token
125 tokens

To scale: P = 1,717 instruction tokens (measured from the installed prompt) and the chunk c in the highlight colour; the gleaning call re-sends both plus the first answer and the 34-token "you missed entities" message. Predict before dragging: at graphrag's default 1,200, how many prompt tokens does each text token cost in the first call? Formula: (P + c) / c.

The measured extraction table, and graphrag's source quoted (depth)

Qwen3-4B on the first 40 paragraphs: distinct pairs per paragraph 5.83 to 5.90 with gleaning, 40.0 s a paragraph. Title recall: noun phrases 64 of the 150; the 4B with graphrag's prompt 23 of the first 40 against 26 for the untyped prompt with the 1.7B measured.

graphrag v3.3.0, packages/graphrag/graphrag/prompts/index/extract_graph.py, lines 15 and 23 (record formats); chunking in config/defaults.py lines 60 to 63; entity types lines 147 to 149
("entity"<|><entity_name><|><entity_type><|><entity_description>) ("relationship"<|><source_entity><|><target_entity><|><relationship_description><|><relationship_strength>)
graphrag v3.3.0, packages/graphrag/graphrag/index/operations/extract_graph/graph_extractor.py, lines 101 to 119 (abridged)
if self._max_gleanings > 0: # default 1: defaults.py line 150 for i in range(self._max_gleanings): messages_builder.add_user_message(CONTINUE_PROMPT) # "MANY entities and relationships were missed..." response = await self._model.completion_async(messages=messages_builder.build()) results += response.content if i >= self._max_gleanings - 1: break # last round: no "are there more? Y/N" call ...

The parser upper-cases every name (clean_str(record_attributes[1].upper()), lines 146 to 147) and the merge step groups entities across chunks by exact (title, type) (extract_graph.py line 108). Descriptions of one entity from many chunks are summarised by another LLM call once there are two or more (description_summary_extractor.py lines 63 to 68).

Extraction without a language model

graphrag also ships a "fast" indexing method (config/enums.py lines 44 to 54) that replaces the LLM with classic NLP: noun phrases from a part-of-speech tagger become nodes, and two phrases in the same text unit get an edge weighted by pointwise mutual information (PMI, how much more often they co-occur than chance: p(x,y) log2(p(x,y) / (p(x) p(y))), graphs/edge_weights.py line 22).

Over all 9,760 HotpotQA paragraphs it took 25.0 s on one CPU core (about 2.6 ms a paragraph, zero LLM tokens) and found 133,664 phrases, 73,428 distinct, 59,459 of them (81%) in a single paragraph measured (load average 8.1 from other jobs). The most frequent nodes are month names (September in 550 paragraphs): hubs that join unrelated paragraphs. A paragraph's own subject, its Wikipedia title, appears among its phrases (upper-cased exact match) for only 3,243 of 9,760 paragraphs (33%) measured.

What the noun-phrase extractor cannot keep (depth)
A phrase is kept only if every token is plain letters, digits or hyphens (has_valid_tokens, regex_extractor.py), so "Hey Pa! There's a Goat on the Roof" or "Ernst Willi Messerschmid's" can never be nodes, and "New York" becomes "YORK" because "NEW" is in its stop list. Its default extractor is TextBlob-based and, per its docstring, "the extractor used in the first bencharmking of LazyGraphRAG" (regex_extractor.py line 32; the typo is theirs).

4. Entity resolution: is "Doyle" the same node as "Arthur Conan Doyle"?

Entity resolution sounds like housekeeping; it decides whether the graph connects at all. A bridge question's two paragraphs are joined only if the mention in one ("Temple", "Shirley Temple Black") and the subject of the other (the article "Shirley Temple") become the same node. Merge too strictly and the graph falls into islands; too loosely and unrelated things fuse ("James Bond" the character and "the James Bond series"; "Labrador" the region and "Labrador Retriever").

Gold without hand labels. HotpotQA gives two checks for free: every paragraph's title is its subject, so its extraction should contain a mention that resolves to that title (title recall); and every bridge pair is joined by a mention of one's title in the other, so a good graph should join them (link recall). Four rules, strictest first, applied to graphrag's noun phrases (s_entities.py): exact (upper-cased string equality, what graphrag's merge does); normalised (lower case, punctuation, articles and Wikipedia's parenthetical removed: "Kiss and Tell (1945 film)" = "kiss and tell"); token subset (the mention's words are a subset of a title's and cover at least half of them: "Kerensky" = "Alexander Kerensky"); embedding (nearest title by bge-small cosine, kept above 0.85).

Looser matching connects more bridge pairs and is wrong more often

Left: bridge pairs whose two gold paragraphs end up sharing a node, of 160, noun-phrase graph over all 9,760 paragraphs. Right: of 30 random merges each rule adds beyond exact matching, how many a hand check found right (subset paragraphs; src/inputs/merge_labels.json); 30 is a small sample, so read it as "most", "about half", "two thirds" measured.

ruletitle recall, all 9,760bridge pairs joined, of 160extra mergesambiguousextra merges right, hand-checked
exact3,2437100(baseline)
normalised4,225843,74120127 of 30
token subset6,48811425,1859,04516 of 30
embedding ≥ 0.855,66610713,16520120 of 30

"Extra merges": mentions a rule maps to a title that exact matching does not; "ambiguous": mapped to more than one title (two films called "Camille"). Hand check read in context by the page author.

The 30 hand-checked merges per rule (depth)

Every wrong merge adds edges between unrelated paragraphs, and graph algorithms amplify edges: a PageRank walk or a community will happily cross a false bridge. Production systems therefore resolve in stages: cheap normalisation for everything, blocking (compare only names that share a token or a sound), an embedding or LLM judgement on the candidate pairs, and, where it exists, linking to an external identifier (a Wikidata id, a customer number) that settles the question. graphrag does the first stage only; LightRAG 1.5.7 does not even case-fold names (utils.py lines 5391 to 5393, normalize_entity_name).

An LLM extraction on the same gold gives better names and a sparser graph: the root agent runs' Qwen3-1.7B names contain the paragraph's own title for 269 of 394 subset paragraphs against 137 for noun phrases, but after graphrag's pruning only 278 of its 3,109 entity nodes survive, because most of its names occur in one paragraph only.

The LLM extraction against noun phrases, in full (measured, depth)

The root's agent runs extracted the 394 subset paragraphs with Qwen3-1.7B and a short one-call prompt (81,368 prompt and 80,429 output tokens, 951 s, about 2.4 s a paragraph) measured, root agent runs. Its names contain the paragraph's own title for 269 of 394 paragraphs against 137 for noun phrases, and join 20 of 29 bridge pairs against 15 (24 with embedding resolution) measured. Better names, sparser graph: after graphrag's pruning only 278 of its 3,109 entity nodes survive and the largest connected component holds 145, because almost all its names occur in one paragraph and graphrag drops names seen in fewer than 2 text units, whereas generic noun phrases ("HEAD COACH", "RUSSIA") recur.

Resolution on this page's graphrag-prompt extractions, the same tables:

5. Communities: Louvain, Leiden and the hierarchy

A community is a set of nodes more densely linked to each other than to the rest. GraphRAG summarises communities, so "what is this corpus about" becomes "what is each community about". A partition is scored by modularity: the edge weight inside communities minus what a random graph with the same degrees would put there.

Q = (1 / 2m) Σij [ Aij − γ ki kj / 2m ] δ(ci, cj)
Aij
edge weight between nodes i and j
ki
total edge weight at node i (its degree)
m
total edge weight of the graph
γ
resolution: higher gives more, smaller communities (graphrag uses 1.0)
δ
1 when i and j are in the same community, else 0

Louvain (Blondel et al. 2008) maximises Q greedily: move each node to the neighbouring community that raises Q most, collapse each community into one node, repeat. Its flaw: a node that held a community together can move out, leaving the rest disconnected. Leiden (Traag, Waltman and van Eck 2019) adds a refinement phase between moving and collapsing, in which each community is re-split from singletons and nodes may only join well-connected sub-clusters; it guarantees connected communities.

Same graph, same move: Louvain keeps a community whose bridge left; Leiden's refinement splits it

illustrative toy graph of ten nodes, drawn by hand to show the failure the Leiden paper describes; colours are communities.

The Leiden paper found Louvain leaving "up to 25% of the communities ... badly connected and up to 16% ... disconnected" on its test networks, the 16% on DBLP after several iterations (arXiv 1810.08473 v3, abstract and section IV) published. graphrag calls graspologic-native's hierarchical Leiden with max_cluster_size=10, use_lcc=True (keep only the largest connected component) and seed 0xDEADBEEF (resolution 1.0, randomness 0.001): level 0 holds a few big communities, and every one with 10 or more members is split again one level down until none splits. Global search reads one level (default 2): lower levels are fewer, broader summaries.

A real GraphRAG index: the same graph at level 0 and level 1
Thousands of entity nodes laid out as a force-directed graph, coloured by a dozen large level-0 Leiden communities
(a) Level 0: a dozen broad communities, the root summaries.
The same graph with the same layout, now coloured by many smaller level-1 communities inside the level-0 ones
(b) Level 1: each root community split again; the colours fragment inside the same regions.

What a real GraphRAG index looks like: Leiden communities over the MultiHop-RAG news corpus, node size proportional to degree. Edge et al., "From Local to Global: A GraphRAG Approach to Query-Focused Summarization", Figure 4, arXiv 2404.16130 v2, CC BY 4.0; resized.

Measured on the fast-path graph with graphrag's own functions in order (s_communities.py): PMI weights, then prune_graph at its defaults (drop phrases in fewer than 2 text units, the single highest-degree node, and edges below the 40th percentile of weight), then cluster_graph.

Nodes, edges and communities per level, subset and full graph (measured table)
graphphrasesedgesafter pruningcommunities per levelLouvain, disconnected
subset, 394 paragraphs3,79139,065500 nodes, 2,539 edges18, 61, 460 of 19
all 9,760 paragraphs73,4281,060,52213,968 nodes (19%), 160,523 edges28, 361, 1,322, 1,552, 246, 8, 20 of 30

measured, deterministic (seeded). Communities per level read left to right from level 0. Louvain is networkx's (seed 0) on the same pruned largest component, for comparison only.

Two lessons. Pruning is not a detail: only 19% of the phrase nodes survive it, almost all of the cut being phrases seen in one paragraph, which link nothing. And pruning does not cut hubs: it removes only the single highest-degree node, so month names survive among the most connected members of the subset's level-0 communities ("JULY" heads one). Louvain produced no disconnected community on either graph here (Leiden's level 0 none either, by construction): the paper's 16% is an upper range on large networks after several iterations, so Leiden is the safer default, not a rescue every graph needs.

The whole fast path on one question's ten paragraphs

Fig. 2 runs graphrag 3.3.0's own functions over the whole 394-paragraph subset (s_nlp_extract.py, s_communities.py) and takes one question's ten paragraphs step by step: extract, merge, prune, link, cluster, connect. Every name, survivor, edge and community is the recorded output; node positions are networkx's spring layout, seed 0.

  1. Ten text units. The ten paragraphs graphrag sees as ten text units: the question's two gold paragraphs (orange) and eight distractors that share its words (HotpotQA picked them by bigram TF-IDF).
  2. Extract. Every text unit becomes a list of names, one bead each. With the noun-phrase extractor this costs no model call; with an LLM it is one extraction call plus one gleaning call per unit.
  3. Merge. Identical upper-cased names become one node. Highlighted: names found in two or more of these ten paragraphs, the only ones that can connect paragraphs.
  4. Prune. graphrag's defaults over the whole 394-paragraph subset: names in fewer than 2 text units, the single highest-degree node and the weakest 40% of edges go. The survivors rise into the graph.
  5. Link. Surviving names that occur in the same text unit get an edge, weighted by PMI. Only edges among this question's surviving names are drawn.
  6. Cluster. Hierarchical Leiden (max cluster size 10, seed 0xDEADBEEF) assigns every node a level-0 community; colours are communities. Each would get its own report.
  7. Connect. Do the two gold paragraphs share a surviving node? If they do, a graph walk from one reaches the other in two steps; if not, the graph cannot help this question.
The ten paragraphs and their names at this step (the recorded extraction)

The LLM toggle runs the same steps on the root agent runs' Qwen3-1.7B extraction of the same paragraphs: fewer, cleaner names and a sparser graph; on the footballer question it links the gold pair through "CLAUDIO LÓPEZ", a name the noun-phrase extractor cannot keep because of its accent.

Browse the subset's community hierarchy (500 phrases, 2,539 edges; pick a level-0 community to see its children)

Top members by degree show what each community is about, and where pruning left a hub in.

graspologic-native's Leiden, read in source (depth)
graspologic-native 1.2.5 (the version graphrag 3.3.0 pins, ">=1.2,<1.3": its pyproject.toml says 1.3 changes the clustering output), packages/network_partitions/src/leiden/
leiden_clustering.rs 123-166 for each cluster: build its subnetwork, run subnetwork_clustering # the refinement subnetwork.rs 171-181 only singleton, well-connected nodes may move subnetwork.rs 236, 247 target chosen at random, weight approximate_exponent(gain / randomness) hierarchical.rs 132-210 level 0 = one Leiden run; every cluster with >= max_cluster_size nodes is re-clustered as its own network one level down, until none splits

Parameters: config/defaults.py lines 71 to 73; graphs/hierarchical_leiden.py lines 17 to 26 (resolution 1.0, randomness 0.001, modularity); global search's default level, cli/main.py lines 404 to 405.

6. Microsoft GraphRAG at query time: global, local, DRIFT, basic

After indexing, graphrag holds entities (with LLM-merged descriptions), relationships, text units, the community hierarchy and one community report per community: a JSON title, summary, an "impact severity rating" from 0 to 10 and a list of findings, written by the model from the community's entities and relationships (prompt 1,915 tokens; reports default to 2,000 words from at most 8,000 tokens of input; claims extraction is off by default). Four query engines read them.

Global search: map-reduce over community reports

The question goes with batches of reports (every community at the chosen level, default 2) to a map prompt that returns key points, each scored 0 to 100 for how much it helps ("An 'I don't know' type of response should have a score of 0"); the reduce step keeps points scored above 0, sorts them, packs them up to 12,000 tokens and writes the answer in one call. The paper's own words: "Answers with score 0 are filtered out." (Edge et al., section 3.1.6). Fig. 3 runs it on this page's subset, every number from the recorded run:

  1. Reports, written at index time. The subset's fast-mode index has 18 level-0 communities (a block's height is its member count); one report call each, 72,672 prompt tokens of paragraphs in all, wrote a summary (the glass plates). Only 7 of the 18 came back as the valid JSON the prompt asks for; the rest were used as plain text.
  2. Map: the question goes to every report. One call per report here (graphrag batches several per call).
  3. Scores: the filter barely filters. A bar's height is the report's best point score. graphrag drops points scored 0; over the five questions Qwen3-4B scored 88 of 90 report answers 85 or more and only 1 at 0, so nearly every report passes to the reduce step.
  4. Reduce: one call writes the answer. For the themes question, 36 kept points went into it: 19 calls and 21,884 prompt tokens in all.
  5. Breadth, against one search. The tiles are the subset's 394 paragraphs (where a tile sits is layout only). The kept points came from reports covering 367 of them; the dense top 10 reads 10, in one call of 1,850 prompt tokens.

Measured here, small-scale (Qwen3-4B, graphrag's own report, map and reduce prompts, s_global.py): each of five corpus-wide questions cost 19 calls and about 21,850 prompt tokens by map-reduce, against one call and 1,602 tokens for the dense top 10, 14 times as many, and 81 s against 6.9 s with Qwen3-4B measured. The extra calls buy breadth: the points that reached the reduce step came from reports covering on average 366 of the 394 paragraphs, against 10 for the top 10; asked for the main themes, map-reduce named the subset's clusters (the Russian Civil War, sports teams, the James Bond films) where the top-10 answer described whichever paragraphs matched the word "themes". Nobody judged these answers (a 4 B judge on five questions would be noise).

The two answers to this question (Qwen3-4B, recorded)
The measured global-search table, and graphrag's map prompt and reduce code (depth)

The subset's fast-mode index had 18 level-0 communities, so 18 report calls (72,672 prompt tokens of paragraphs), with report and answer lengths shortened so a laptop model can finish. Both models wrote malformed reports: graphrag's report prompt asks for JSON, and only 7 of 18 (4B) and 2 of 18 (1.7B) were valid; the rest were used as plain text.

graphrag v3.3.0, prompts/query/global_search_map_system_prompt.py line 21; query/structured_search/global_search/search.py lines 333 to 375
- Importance Score: An integer score between 0-100 that indicates how important the point is in answering the user's question. An 'I don't know' type of response should have a score of 0. reduce: keep points with score > 0, sort by score, descending, append until max_data_tokens (12,000) then one call writes the answer from them (no points left: a canned "I do not know" answer)

Report defaults: prompts/index/community_report.py; config/defaults.py lines 82 to 83 (length, input), line 132 (claims off); engines in query/factory.py.

What it costs and buys, published. One map call per batch of reports plus one reduce call per question: with hundreds of communities, hundreds of calls. On two corpora (podcast transcripts, about 1 M tokens; news, about 1.7 M), 125 generated "sensemaking" questions each, an LLM judge preferred the global approaches over vector RAG on comprehensiveness in 72 to 83% of pairs and on diversity in 62 to 82% (Edge et al., v2, section 5.1) published; the range includes the text-summarisation baseline TS, which also beats vector RAG, and an LLM judge's preference for longer, broader answers is not correctness (LLM-as-judge). Indexing the podcast corpus took 281 minutes with gpt-4-turbo; the paper reports no token or dollar cost for indexing.

Context per query, and dynamic community selection (published and vendor, depth)

The LightRAG paper's back-of-envelope for its Legal corpus is 610 level-2 communities of about 1,000 tokens each read per query (Guo et al., section 4.5); the GraphRAG paper's Table 2 shows the other side, answering from the root level (C0) with 26,657 context tokens on its Podcast corpus against 1,014,611 for summarising the raw text (2.6%) published.

Microsoft's later dynamic community selection walks the hierarchy from the top, asking the model to rate each report 0 to 5 and descending only into relevant ones (query/context_builder/dynamic_community_selection.py, off by default); its blog reports about 77% lower cost than static global search at level 1 with no significant quality difference (Microsoft Research, 2024-11-15) vendor.

Local search: start from entities

For a question about something specific, graphrag embeds the question, finds the nearest entity descriptions (not the nearest chunks), and assembles a context from those entities' relationships, the text units they came from and their communities' reports, in fixed shares of a 12,000-token budget, top 10 entities and 10 relationships (config/defaults.py lines 265 to 270; mixed_context.py lines 175 to 208).

The GraphRAG paper does not evaluate local search; it is documented and shipped, not benchmarked there.

Local search's context window, to scale: half text, the rest graph

DRIFT: global first, then local follow-ups

DRIFT (Dynamic Reasoning and Inference with Flexible Traversal) combines the two, and is the mode Microsoft built for local questions:

Microsoft's blog reports DRIFT preferred over local search in 78% of comparisons on comprehensiveness and 81% on diversity, on 50 local questions over 5,000+ AP news articles, judged by an LLM (Microsoft Research, 2024-10-31) vendor; it gives no cost. Basic search is plain vector RAG over the text units, top 10 (basic_search/basic_context.py), so the same index answers lookups cheaply: the baseline every graph method has to beat.

DRIFT: a guessed report finds the right communities, then local searches chase follow-ups

Defaults from config/defaults.py lines 99 to 106 (drift_k_followups 20, primer_folds 5, n_depth 3); the primer is a HyDE-style query expansion (drift_search/primer.py lines 71 to 95).

7. Cheaper graphs: LazyGraphRAG, LightRAG, nano-graphrag, HippoRAG

systemindex withkeepsdropsquery
GraphRAGLLM extraction + gleaning, reportsentities, relations, community hierarchy, reportsglobal map-reduce, local, DRIFT
LazyGraphRAGNLP noun phrases, no LLMco-occurrence graph, communitiesreports written in advanceLLM tests candidates within a relevance budget
LightRAGLLM extraction + gleaningentities and relations, their descriptions embeddedcommunity hierarchykeyword call, then vector search over entities and relations
nano-graphragas GraphRAGGraphRAG's shape in a few filesthe weightlocal, global, naive
HippoRAG (1, 2)LLM named entities and triples, synonymy edgesa phrase (and passage) graphcommunities and summariespersonalised PageRank from the question's entities

LazyGraphRAG (Microsoft Research, November 2024) indexes with noun phrases and their co-occurrence (the fast path of section 3) and spends the language model only at query time: split the question into subqueries, rank chunks and communities by relevance, and let the model test candidates against a relevance test budget (100, 500 and 1,500 in the blog's configurations). Microsoft claims indexing at the cost of vector RAG and 0.1% of GraphRAG's, and "more than 700 times lower query cost" at comparable global-search quality vendor; the win rates exist only as chart images. It is not in the open graphrag package (3.3.0 mentions it only in the extractor comment of section 3) and ships in Microsoft Discovery and Azure Local; not run here.

LazyGraphRAG's claims in full (vendor, depth)
At the lowest budget it costs as much per query as vector RAG with an 8k context and beats every compared method except GraphRAG global search on global questions; at budget 500 it costs 4% of GraphRAG's level-2 global search and beats all eight compared conditions (blog, 2024-11-25, editor's note 2025-06-06); in the later BenchmarkQED study it won all 96 comparisons, all but one significant (2025-06-05) vendor.

LightRAG (Guo et al., HKU, 2024; pip lightrag-hku 1.5.7) extracts like GraphRAG (1,200-token chunks, 100 overlap, one gleaning) but embeds entity and relation descriptions in their own vector stores and builds no hierarchy. At query time the model splits the question into low-level keywords (specific entities, searched against entity descriptions) and high-level keywords (themes, searched against relationships). One query is a keyword call plus an answer call instead of a map over hundreds of communities, which is the source of its cost claim. Run here with a recording stub instead of a model (s_lightrag.py stub), LightRAG made 40 LLM calls to index 20 paragraphs with 85,054 prompt tokens, 4,253 per paragraph, before any output measured.

Read the claims carefully. LightRAG's paper reports beating GraphRAG overall on three of four datasets by small margins (54.8, 52.0, 52.8 against 45.2, 48.0, 47.2) and losing on the fourth (49.6 against 50.4), judged by GPT-4o-mini (arXiv 2410.05779 v3, Table 1) published. HippoRAG 2's authors, re-running LightRAG with Llama-3.3-70B, got a QA F1 of 2.4 on HotpotQA against 75.3 for plain dense retrieval published: each paper runs its rivals with its own model, prompts and judge, so compare on your data with the same generator. The "70 to 90% of GraphRAG's quality at 1/100 of the cost" quoted around the web has no method or source and is not repeated here.

LightRAG with a real local model, its modes and source, and nano-graphrag (depth)

Modes: "local" searches entities with the low-level keywords, "global" relationships with the high-level ones, "hybrid" both, "mix" (the default) both plus chunk vectors, "naive" chunks only.

Source: chunking and gleaning in lightrag.py lines 1097 and 1104, constants.py line 17; keywords in prompt.py lines 489 to 490; modes in operate.py lines 5235 to 5283; descriptions of an entity are joined as text and only summarised by the model once there are 8 of them or 1,200 tokens (operate.py lines 436 to 440).

Run with Qwen3-4B behind llama-server and bge-small as its embedder (s_lightrag.py; one change from its defaults: a 16,000-token query budget instead of 30,000, to fit a 24,576-token window): indexing the first 40 subset paragraphs took 80 LLM calls, 194,159 prompt tokens (4,854 a paragraph) and 31,794 output tokens, 1,246 s, and built a graph of 349 entities; it logged format errors on several relation records, which it drops measured. On the 4 questions whose two gold paragraphs are among those 40 (far too few to compare modes: read this as "it works end to end on a local model"), the answer contained the gold answer for naive 2, local 1, global 2, hybrid 3 and mix 3 of 4.

nano-graphrag (0.0.8, 2024) re-implements GraphRAG's shape in a few files: 1,200-token chunks, one gleaning, graspologic's hierarchical Leiden on the largest component with max_graph_cluster_size 10 and the same seed, community reports, and local, global and naive modes, default global at level 2 (nano_graphrag/graphrag.py lines 70 to 81; base.py lines 11 to 14). Its OpenAI client is created with no arguments (_llm.py lines 20 to 23), so pointing it at a local server needs the OPENAI_BASE_URL variable or a custom function. Last PyPI release 0.0.8.2, 2024-10-19; not run here because LightRAG covers the same shape and is maintained.

HippoRAG: personalised PageRank instead of summaries

HippoRAG (Gutiérrez et al., NeurIPS 2024) ignores communities and treats the graph as an associative memory. Indexing: an LLM extracts named entities, then triples, from each passage; phrases whose retrieval-encoder cosine exceeds 0.8 get a synonymy edge. Query: extract the question's entities, link each to its most similar graph node, and run personalised PageRank (PPR) from them; a passage scores the probability mass of its phrases.

Fig. 4 runs it on an illustrative toy graph in the shape of the running example: triples a model might extract from four passages (A the 1945 film, B Shirley Temple, C the Broadway play, D a radio show). The page computes exact power iteration with d = 0.5 and the reset weighted by specificity; a column's height is the node's probability, and the plinths at the front are the passage scores.

  1. Reset: mass on the question's entities. Kiss and Tell is in passages and Corliss Archer in , so they start with and of the mass. Passage B scores : it shares no word with the question.
  2. One step. Half the mass stays on the reset nodes, half follows an edge. Shirley Temple, linked to both question entities, picks some up, and B scores for the first time.
  3. Two steps. Mass reaches Chief of Protocol and diplomat, B's own phrases; B scores .
  4. Three steps. Each step moves less; B scores .
  5. Converged, 30 iterations. B scores against 0 at the start, still below C () and D (), which repeat the question's names. In a real index thousands of passages score 0, so B now enters the top 5: that is the hop. It does not reach the top 2.
p = (1 − d) r + d W p
r
reset vector: mass on the question's nodes, each weighted by its node specificity 1 / (number of passages containing it), so rare names count more
W
the graph's edge weights, each column normalised to sum to 1
d
probability of following an edge rather than jumping back to r: 0.5 in the paper's experiments (run_hipporag_main_exps.sh line 4; the class default is 0.1)
p
the stationary probability of each node

The toy shows both sides of the measured result in section 8: the walk reaches the bridge passage, which shares no word with the question, but it still ranks below passages that merely repeat the question's names. Published: HippoRAG (ColBERTv2) recall@5 of 89.1 on 2WikiMultiHopQA against 68.2 for ColBERTv2 alone and 51.9 against 49.2 on MuSiQue, but 77.7 against 79.3 on HotpotQA, where it loses; online retrieval "10 to 30 times cheaper and 6 to 13 times faster" than iterative retrieval with IRCoT (arXiv 2405.14831 v3, Table 2 and appendix G) published. HippoRAG 2 (2025) adds passages as graph nodes seeded by dense similarity, the shape section 8 runs.

HippoRAG 2 in detail (published)
HippoRAG 2 seeds passages with reset weight 0.05 times the passage's dense score, links the query to triples rather than entities, and filters triples with the model; with NV-Embed-v2 and Llama-3.3-70B it reports recall@5 of 96.3 on HotpotQA against 94.5 for NV-Embed-v2 alone, and QA F1 averaged over seven datasets of 59.8 against 57.0, with GraphRAG at 49.6 (arXiv 2502.14802 v2, Tables 2 and 3) published.

8. Multi-hop, measured: graph traversal against plain retrieval and the agent

All systems rank the same 9,760 paragraphs for the root's 200 HotpotQA questions (160 bridge, 40 comparison), with no LLM call at retrieval time (s_ppr.py, CPU, deterministic). Graphs: PPR over a phrase graph (HippoRAG 1 shape: noun phrases, co-occurrence plus 113,377 synonymy edges); PPR over passages and phrases (HippoRAG 2 shape); and title links (an edge from paragraph i to j when i names j's title, 11,236 edges: HotpotQA's own hyperlink graph, recovered by string matching), used for PPR or for expansion: keep the dense top 2, then add the paragraphs they link to or that link to them. bge-small is the dense model because Qwen3-Embedding declares HotpotQA in its training data.

Reading it. PageRank over the noun-phrase graph is worse than dense retrieval (79 against 137 at 5): co-occurrence edges are not relations, and a walk from "BOLSHEVIKS" spreads over every paragraph about Russia. Seeding it with dense scores (HippoRAG 2's shape) recovers some of it, pruning hubs a little more, still below dense: the same direction as HippoRAG's own HotpotQA row (77.7 against ColBERTv2's 79.3) published, with a weaker graph. Edges that are real relations change the picture: expanding the dense top 2 along title mentions puts both gold paragraphs in the top 5 for 169 questions against 137, gaining 37 and losing 5, nearly all on bridge questions (132 against 98). Two caveats: the title graph is HotpotQA's own construction (section 2), so the dataset hands it the right edges; and a corpus without one page per entity (contracts, tickets, chat logs) has no titles to link, which is what LLM extraction and entity resolution are for.

Edges that are real relations help; co-occurrence edges hurt

Questions with both gold paragraphs in the top k measured. Hover or tap a point for its value.

The same question through two retrievers: watch where the second gold paragraph comes from

Each of the 200 questions ranked over all 9,760 paragraphs; gold paragraphs have an orange border. Default: the dense top 5 against the same search expanded along title mentions; when a gold paragraph arrived through a link, the sentence that carries the link is shown, with Qwen3-1.7B's answer from each list. Data: s_ppr.py, s_examples.py, deterministic.

Every system at k = 2, 5 and 10, with gains and losses against dense (table)

Also: PPR reset on the question's noun phrases linked to their nearest node (424 of 475 matched exactly), weighted by specificity; the HippoRAG 2 shape adds paragraphs as nodes joined to their phrases, reset 0.05 times each paragraph's dense score; "pruned" removes the 364 phrases found in more than 20 paragraphs; 6,288 paragraphs have at least one title link; hybrid is reciprocal rank fusion of BM25 and dense, k = 60.

systemboth in top 2top 5top 10bridge, top 5vs dense at 5: gained / lost
BM25451051477710 / 42
dense (bge-small)9413716498(reference)
hybrid (RRF)8214316310417 / 11
PPR, phrase graph36791206316 / 74
PPR, passages + phrases39921327625 / 70
same, hubs pruned38941337724 / 67
PPR, title links7014016310717 / 14
expand along title links9416918713237 / 5
Predict: with the same 1.7 B model, the root's ReAct agent (it searches as many times as it likes) reaches F1 0.411 and one dense search with the top 5 in the prompt 0.402. How often does the agent's trajectory contain both gold paragraphs, against the dense top 5's 137?

Does the recall survive the generator? Each retriever's top 5 went into the root agent runs' tuned single-shot prompt with Qwen3-1.7B (s_qa.py). HotpotQA F1 over the 200 questions: dense 0.402, hybrid 0.417, PageRank over passages and phrases 0.408, PageRank over title links 0.423, expansion along title links 0.464 (exact match 0.300 against 0.260), and the ReAct agent 0.411 measured. Only the title-link expansion is clearly ahead of dense: +0.063 F1, paired bootstrap 95% interval 0.015 to 0.110; the others are within noise of dense. It costs 715 prompt tokens a question against 2,258 for the agent, because the graph did at index time what the agent does with extra calls. With Qwen3-4B the ordering holds and the gaps widen (title-link expansion 0.588 against dense 0.490 and the agent 0.574, which now pays, at a third of its tokens; details below) measured. The edges are still HotpotQA's own hyperlinks.

The answer tables (Qwen3-1.7B table; Qwen3-4B with intervals)

Qwen3-4B: dense 0.490, hybrid 0.530, PageRank over passages and phrases 0.511, PageRank over title links 0.555 (gain interval 0.016 to 0.115), title-link expansion 0.588 (0.051 to 0.145), and the agent 0.574 (0.021 to 0.146) at 2,318 prompt tokens a question measured: a better model makes the agent loop pay, and the graph expansion still matches it with a third of the tokens.

9. What a graph costs, and when it pays

Indexing cost is a sum over LLM calls, each billed for its whole prompt. For graphrag's standard method, per text unit of c tokens:

Tin ≈ (P + c) + (P + c + o1 + 34)     Tout ≈ o1 + o2
P
the extraction prompt's fixed instructions and examples: 1,717 tokens measured
c
the chunk (1,200 by default)
o1, o2
tokens the model writes in the extraction and the gleaning call (34 = the gleaning message); measured here with Qwen3-1.7B on 125-token paragraphs: 922 for both calls together measured

plus one summarisation call per entity seen in two or more chunks, one report call per community (prompt 1,915 tokens plus up to 8,000 of context), and the embeddings. The Cost calculator adds these up with every assumption visible. The one published itemised bill:

Queries cost too: 10.7 s per question for GraphRAG and 13.3 s for LightRAG against 0.3 s for dense retrieval in the same table published.

Indexing the same 11,656 passages: GraphRAG reads 12.6 times the input HippoRAG 2 does

MuSiQue's 11,656 passages indexed with Llama-3.3-70B by HippoRAG 2's authors: input / output tokens of 115.5 M / 36.1 M for GraphRAG, 68.5 M / 18.3 M for LightRAG and 9.2 M / 3.0 M for HippoRAG 2, and 277, 235 and 99.5 minutes (arXiv 2502.14802 v2, Table 12) published; about 9,900 input tokens per passage for GraphRAG derived: 115.5 M / 11,656; and 12.6 times HippoRAG 2's input: 115.5 / 9.2.

When a graph pays. When (a) the questions are global or relational, not lookups; (b) the corpus is stable, so the index is built once and read many times (updates re-extract and re-cluster; LightRAG and graphrag's incremental methods reduce, not remove, this); (c) entities are what the corpus is about (people, companies, products, cases), so extraction finds real relations; and (d) someone owns entity resolution. When any of these fails, the cheaper rungs win: hybrid search with a reranker for lookups, the agent loop for occasional multi-hop questions (the root's agent runs), an NLP-indexed graph with query-time LLM work (the LazyGraphRAG shape) for occasional global questions, and SQL for anything that is already a table.

10. Structured retrieval: text-to-SQL

When the data is already a table, retrieval should be a query. Text-to-SQL asks a language model to translate the question into SQL; the database computes the answer exactly, over every row, with joins and aggregates. The model needs the schema (tables, columns, keys), and schema linking is where most errors start ("stations" in a question about the stadium table; two databases both with a singer table).

How it is scored. Execution accuracy runs the predicted and the gold query and compares results; exact match compares the SQL's parsed structure and rejects correct queries written differently. Execution accuracy has the opposite flaw, false positives: a wrong query can return the right rows on a small database by luck. Zhong et al. measured single-database execution accuracy accepting wrong queries 6.5% of the time on average across Spider submissions, up to 9.0%, and proposed test suites of extra databases (arXiv 2010.02840, Table 2) published.

The same method on bigger, messier databases: 86.6% falls to 5.68%

DAIL-SQL with GPT-4o, execution accuracy, as re-run by Spider 2.0's authors (arXiv 2411.07763 v2, Tables 4 and 5) published. The drop is mostly schema size and dialect, which is a retrieval problem.

The benchmarks, dated (Spider 1.0, BIRD, Spider 2.0, leaderboards)
  • Spider 1.0 (Yu et al. 2018): 10,181 questions, 5,693 SQL queries over 200 databases in 138 domains; the dev split (used here) is 1,034 questions over 20 databases (arXiv 1809.08887 v5). The best model at publication reached 12.4% exact match; prompted GPT-4o reaches 85.3 to 86.6% execution accuracy with DIN-SQL or DAIL-SQL in Spider 2.0's re-runs published. Its databases are small and clean, which is why newer benchmarks moved on.
  • BIRD (Li et al. 2023): 12,751 questions over 95 databases totalling 33.4 GB, with dirty values and "external knowledge evidence" (a hint such as which column means what). GPT-4 reached 34.88% test execution accuracy without the evidence and 54.89% with it; humans 92.96% (arXiv 2305.03111 v3, Table 2) published. The leaderboard's best test score read on 2026-10-14 is 82.95 (GrainSQL, dated 2026-09-26; bird-bench.github.io) leaderboard.
  • Spider 2.0 (Lei et al. 2024): 632 enterprise tasks over BigQuery, Snowflake and local databases with hundreds of columns and dialect details. An o1-preview agent solved 21.36%; DAIL-SQL with GPT-4o, 86.6% on Spider 1.0 and 57.4% on BIRD, solved 5.68% of Spider 2.0-lite published. The leaderboard's best on Spider 2.0-lite read on 2026-10-14 is 76.23 (dated 2026-07-28; spider2-sql.github.io) leaderboard.

Schema retrieval: the retrieval problem inside text-to-SQL

A real warehouse has thousands of tables; the prompt holds dozens. So the first step is retrieval again, over table descriptions instead of passages. Measured on 100 Spider dev questions (5 per database, seed 0; s_sql_sample.py), pooling all 20 dev databases (81 tables) as if the question did not say which: one document per table, "table in database: columns" (e.g. "singer in concert singer: singer id, name, country, song name, song release year, age, is male"), retrieved by BM25 or bge-small (s_schema_ret.py):

At k = 5, bge-small has every needed table for 98 of 100 questions with 339 prompt tokens, against 5,637 for the full dump; BM25 95 at 340. The top table's database is the right one for 97 (BM25) and 92 (bge-small) of 100. Lexical retrieval is strong here because table and column names are words from the question ("singer", "concert"), the reverse of passage retrieval, where paraphrase favours embeddings.

Five retrieved tables hold everything the query needs for nearly every question

Questions whose every gold table (parsed from the gold SQL with sqlglot) is in the top k tables, and the CREATE TABLE tokens those k tables add to the prompt measured. Dumping all 20 databases costs 5,637 tokens; the question's own database, the standard Spider setting, a median of 220.

Measured end to end with Qwen3-1.7B and Qwen3-4B on the same 100 questions (s_sql_run.py; the result must equal the gold query's rows):

For both models schema retrieval matches the oracle setting (the 4B even gains one) with less than a tenth of the dump's prompt. The dump is cheap to run despite its size: the schema is a shared prefix, so llama-server recomputed only 81 tokens per question; the cost of a big schema is accuracy, not time.

Retrieved tables match the oracle schema; the full dump is the worst real option

Correct of 100 by execution, strict column order measured. Without a schema the model invents table names; with the dump (5,718 prompt tokens) the 1.7B named the right database for only 60 questions.

One question, four prompts: what the model is shown, and what it wrote

100 Spider 1.0 dev questions (5 from each of the 20 dev databases, seed 0). Bars are prompt tokens of schema, to scale; green tables are read by the gold SQL. Below: the gold query and its result.

Fig. 5 steps through one question under the four prompts; pick any of the 100 with the two menus.

  1. No schema: the question only. The model must guess every table and column name.
  2. All 20 databases dumped. Everything is there, all 81 tables, most of them not needed by the question; the model must also pick the database.
  3. 5 tables retrieved by bge-small. Only the top 5 of the pooled 81 tables; green ones are read by the gold SQL. The model must still pick the database.
  4. The question's own database. The standard Spider setting, the oracle: every table of the right database and nothing else.
The measured text-to-SQL table (both models, four prompts, queries that ran, right database named, prompt tokens)

1.7B: question alone 2 (7 queries even run), all 20 databases 27, 5 retrieved tables 56, own database 56; 4B: 5, 53, 64 and 63. Accepting the same rows with columns in another order (Spider's official evaluation does) adds three to five to each.

Running generated SQL safely. The model writes code that will run against production data: connect with a read-only role, set a statement timeout and a row limit, reject anything but SELECT (parse it; do not regex it), and enforce access with the database's own row-level security rather than with instructions in the prompt (RAG in production measures prompt-level access control leaking). How to check SQL a model wrote, as untrusted input, before it runs is on SQL and data modelling, section 12.

11. Tables as text, SQL plus vectors, and graph query languages

Retrieving rows as text. The alternative to writing queries is to serialise each row into text ("singer: name Rose White; country France; age 41"), or each small table into Markdown, embed it and retrieve it like a passage. That works for lookups of descriptive records (a product's specification, one customer's ticket) and fails for anything that counts, sums, ranks or joins, for the reason in section 1: 23 of the 48 Spider aggregates here read more than 10 rows measured. A useful hybrid keeps both: rows retrievable as text for "find the record about X", the table queryable for "how many X".

SQL and vectors in one query. Where structured filters and semantic similarity meet ("cheap hotels near the sea with good reviews about quiet rooms"), put both in one engine: a vector column in the table and a query that filters with SQL and orders by distance. In PostgreSQL with pgvector: SELECT name FROM hotels WHERE price < 120 AND city = 'Nice' ORDER BY review_embedding <=> $1 LIMIT 5. The language model only extracts the filter values ("self-query", on The retrieval pipeline); how the filter and an HNSW index interact (too few rows after filtering; pgvector 0.8's iterative scans) is on Vector indexes from the inside and Search and vector databases.

Cypher and SPARQL

The same rows can live in a graph database. Spider's concert_singer database loaded into Kùzu 0.11.3 (an embedded Cypher database, in process like SQLite; its repository was archived in October 2025, last push 2025-10-10, read 2026-10-14, so 0.11.3 is its last release and a teaching engine here, not a recommendation) becomes 9 stadiums, 6 singers and 6 concerts as nodes, with 6 HELD_AT edges and 10 PERFORMED_IN edges (s_kuzu.py).

The Kùzu schema and the four example questions on both engines (depth)

Graph query languages pay off when the question is a path of unknown length ("who is connected to this account within three transfers"), which SQL expresses only with recursive common table expressions; for fixed short paths a relational database is often enough (on NoSQL in practice, section 8, Postgres was fastest up to three hops against the graph engines). For language models, Cypher is the harder target: on CypherBench (11 Wikidata property graphs, over 10,000 questions) the best zero-shot execution accuracy reported was 61.58% (Claude 3.5 Sonnet) and 60.18% (GPT-4o) (arXiv 2412.18702 v2, Table 3); Neo4j's Text2Cypher dataset has 44,387 question and query pairs for fine-tuning (arXiv 2412.10064) published. Measured here on all 45 concert_singer dev questions, same rows on both engines: Qwen3-1.7B wrote correct SQL for 28 and correct Cypher for 11, and only 29 of the 45 Cypher queries even parse and run; Qwen3-4B, SQL 36 against Cypher 16 measured. Most failures are SQL habits carried into Cypher (a GROUP BY clause, a WHERE in the wrong place, two statements in one answer): a small model has seen far more SQL than Cypher, the practical argument for keeping relational data relational.

The SQL against Cypher table (measured)
The join table becomes an edge: SQL spells the join, Cypher draws the path
"List singer names and number of concerts for each singer." Spider gold SQL, then hand-written Cypher; same rows on both engines, 4 of 4 example questions measured
SELECT T2.name, count(*) FROM singer_in_concert AS T1 JOIN singer AS T2 ON T1.singer_id = T2.singer_id GROUP BY T2.singer_id MATCH (s:Singer)-[:PERFORMED_IN]->(c:Concert) RETURN s.name, count(c)

SPARQL over curated graphs such as Wikidata is the older form of the same idea, knowledge-graph question answering; it needs the graph's identifiers, which is why open-extraction graphs rarely use it. Temporal graphs for an agent's own memory (Graphiti and Zep) are on Context engineering; how relational engines plan joins on Topic: databases.

12. Choosing

the question looks likeusewhy, and what it costs
a lookup ("what does clause 7 say")hybrid search + rerankerone passage holds the answer; a graph adds index cost and no recall (section 8: PPR over a noun-phrase graph lost to dense)
a chain over entities, occasionallyagent loop with search as a toolno index to build; pays per question (the root's ReAct agent: 2,258 prompt tokens per question against 727 for one search, F1 0.411 against 0.402)
chains over entities, as the main workloadan entity graph with traversal or PPR (HippoRAG 2 shape), plus dense seedspays at index time; only as good as extraction and entity resolution (sections 4 and 8)
"what is this corpus about", occasionallyNLP-indexed graph, LLM at query time (LazyGraphRAG shape), or map-reduce over chunk clustersno LLM indexing bill; quality claims are vendor-only so far
"what is this corpus about", often, stable corpusGraphRAG global search, or dynamic community selectionthe indexing bill (section 9) amortised over many questions
counts, sums, rankings, joinstext-to-SQL with schema retrieval and a read-only connectionexact answers over all rows; errors are schema linking, measured by execution accuracy
paths of unknown length (fraud rings, supply chains)a graph database and Cypherpaths are native; models write Cypher less reliably than SQL (section 11)
filters plus meaningSQL WHERE plus vector ORDER BY in one engineone query, one consistency model (pgvector)

13. Depth: mistakes worth a check, and interview rehearsal

Mistakes the core does not already show (4)
  • Measuring entity resolution by eye. The graph you draw in a demo is not connected the way you think: measure link recall on a labelled sample (title and bridge pairs give it for free on HotpotQA) before trusting traversal.
  • Quoting indexing cost per chunk without the prompt. Count prompt tokens with the real prompt (s_prompt_tokens.py); the instructions, not the text, are most of the bill for small chunks.
  • Paying for gleaning without checking it. Count distinct (name, type) pairs with and without the second call on a sample before paying for it.
  • Scoring text-to-SQL by execution on one small database. Use test suites or several database states for a real evaluation.
Interview rehearsal (three design questions)

System design: an assistant over a company's contracts, CRM and support tickets that answers "which enterprise customers with renewals next quarter have open P1 tickets mentioning data loss?" Route by question type. The structured part (customers, renewals, ticket priority) is SQL over the CRM and ticketing databases: schema retrieval over table descriptions, generated SELECT on a read-only replica with row-level security per user, timeouts. The unstructured part ("mentioning data loss") is hybrid search over ticket text, filtered by the customer and ticket ids the SQL returned (or pgvector in the same query). Contract terms that matter (renewal dates, parties) are extracted at ingestion into columns, not left for retrieval. No GraphRAG unless users ask relational questions across accounts often; then an entity graph keyed on CRM ids, which solves entity resolution with the company's own identifiers. Evaluate each path separately (execution accuracy on a labelled SQL set, recall@k on tickets), log every query and its SQL, cache nothing that crosses permissions.

When would you not build a graph even though the questions are multi-hop? When they are rare (an agent loop pays per question, no index), when the corpus changes daily (re-extraction cost), or when there are no stable entities to resolve. Measure the agent first; the root's lab gives its token bill.

Text-to-SQL accuracy is 85% on Spider; why does that not predict production? Spider databases are small and clean, the schema fits the prompt and execution accuracy has false positives. Production has thousands of tables, dirty values and dialects: Spider 2.0 dropped the same methods to about 6%.

The root page's first small graph, as it was measured (moved here when the root's Agentic lab was retired, 2026-10-24; 2 min)

Recorded in the root page's src/agent (its graphrag.json, which this page's build also reads). Microsoft's graphrag package sizes its extraction prompts and thousands of calls for large hosted models; a LightRAG-style extraction with one call per paragraph gives the indexing-cost shape at a scale the laptop can run.

  • Build. The own paragraphs of the first 40 test questions were indexed LightRAG-style (Qwen3-1.7B lists entities and relations, one call per paragraph; the paragraph's title is always an entity; entities merged by normalised name), with Louvain communities (networkx; Leiden is the same idea with a guarantee of connected communities) and a summary per community of 8 or more entities. Indexing 394 paragraphs that hold 53,062 tokens of text cost 161,797 generator tokens (81,368 in, 80,429 out: about 3 tokens of work per token indexed) and 15.9 minutes of generation, plus 36,720 tokens and 99 s to summarise 92 of the 131 communities. At this rate the whole 9,760-paragraph corpus would take about 6.5 hours of extraction on the laptop; the published GraphRAG indexed about 1 million tokens of podcasts in 281 minutes with a hosted model.
  • Names. The graph has 3,160 entities, only 284 of which appear in more than one paragraph: a small model's names rarely match across paragraphs, which is why real systems add entity resolution (section 4).
  • Local use, one graph hop. Seeds are the dense top 2 paragraphs for the question; the graph adds every paragraph that mentions an entity of the seeds or of the question, ranked by their dense score. With one graph hop both gold paragraphs are in the top 3 for 29 of the 40 questions against 26 for dense search alone; at the top 2 and the top 5 the two tie (19 and 34). The gain is the bridge case: the second paragraph is reached because it mentions an entity of the first ("Viglen" through "Bordan Tkachuk").
  • Global use. No gold answers exist for a question about the whole subset, so the map-reduce answer and the top-10 answer were compared side by side, not scored; the small model makes visible mistakes in both (one global answer puts the Cleveland Browns in the NBA). This is the GraphRAG trade in miniature: a large indexing bill and a larger per-question bill for global questions, in exchange for answers that cover the corpus instead of ten passages.
Every measured number on this page comes from the scripts in this page's src/scripts folder, run on an Apple M1 Pro (10 CPU cores, 16 GB) from 2026-10-14 to 2026-10-15 against the running example of Topic: rag-and-retrieval (its src/data/load.py) and the Spider 1.0 dev databases (CC BY-SA 4.0; dev.json identical to xlangai/spider's validation split). Versions: graphrag 3.3.0 with graspologic-native 1.2.5, nltk 3.9.4 and TextBlob 0.20.1; LightRAG (lightrag-hku) 1.5.7; Kùzu 0.11.3; sqlglot 30.22.0; sentence-transformers 6.1.0 (bge-small on CPU); networkx 3.7. Source quoted from shallow clones at graphrag v3.3.0 (5faaaf4f), LightRAG v1.5.7 (28ff1b05), nano-graphrag v0.0.8 (cddcda71), HippoRAG v1.0.0 (b144c46d) and graspologic-native 1.2.5 (3c989664). Generator runs: Qwen3-1.7B and 4B Q4_K_M in llama-server, through the root agent runs' generator module. Published numbers are labelled and kept apart. Rebuilt to the teaching contract on 2026-10-24.