In short
GraphRAG adds a knowledge graph to retrieval-augmented generation. An LLM reads the corpus once, extracts entities and the relations between them, merges duplicate entities, groups the graph into communities with an algorithm such as Leiden and writes a summary of every community. At query time, local search starts from the entities a question mentions and walks their neighborhood, which helps with multi-hop questions, while global search maps the question over the community summaries and reduces the partial answers, which helps with "what are the main themes" questions that plain vector RAG answers poorly.
Key points
- Vector RAG retrieves passages that look like the question. It struggles when the answer needs facts from several passages joined by an entity, or a view of the whole corpus.
- A knowledge graph for retrieval is built by an LLM: extract entities and relations per chunk, then resolve duplicates. Entity resolution decides whether multi-hop answers work at all.
- Community detection (Leiden, applied hierarchically) plus an LLM-written report per community is what makes corpus-wide questions answerable.
- Local search walks a neighborhood around matched entities; global search runs a map-reduce over community reports. They answer different kinds of questions.
- Indexing is the price: many LLM calls per chunk and per community, and rebuilds when the corpus changes. Lighter variants such as LightRAG trade some of that away.
- Evaluate by question type, against a vector RAG baseline, and check the graph itself: extraction precision and duplicate entities.
Where vector RAG falls short
Standard retrieval-augmented generation splits documents into chunks, embeds each chunk, and at query time retrieves the chunks whose embeddings are closest to the question's. RAG explained covers that pipeline, and hybrid search adds keyword matching for exact names and codes. For a question whose answer sits in one or two passages that resemble the question, this works well. Two kinds of question break it.
The first is the multi-hop question. "Which city is the parent company of Acme Robotics based in?" needs one passage saying who acquired Acme and another saying where that buyer is headquartered. The second passage may never mention Acme, so it looks nothing like the question and similarity search has no reason to rank it. HotpotQA, a benchmark of about 113,000 Wikipedia-based question and answer pairs, was built around exactly this: its authors designed questions that need reasoning over several supporting documents.
The second is the global question: "What are the main themes in these interviews?" or "Which risks come up most across these reports?" No single chunk contains the answer, because the answer is a summary of the whole corpus. Retrieving the top ten chunks returns ten local fragments. Edge et al., in the Microsoft paper that introduced GraphRAG, argue that standard RAG fails on such questions because they are query-focused summarization tasks over a whole corpus rather than retrieval tasks.
- Local fact questions: "What does the warranty cover?" Vector or hybrid RAG is usually enough.
- Multi-hop questions: facts linked through an entity across documents. A graph lets retrieval follow the link instead of hoping both passages rank highly.
- Global sensemaking questions: themes, trends, comparisons across the corpus. Precomputed summaries over groups of related entities give the model something corpus-wide to read.
A graph does not replace vectors. Most GraphRAG systems still embed chunks and entity descriptions, and use similarity search to find where to enter the graph. The graph adds structure that similarity alone cannot recover: which things are the same thing, which things are connected, and which groups of things belong together.
Building a knowledge graph with an LLM
Hand-built knowledge graphs need a schema and curators. GraphRAG-style systems instead let an LLM read every chunk and write the graph. Microsoft's GraphRAG documentation describes the indexing dataflow in stages, and most implementations follow a similar shape:
- Chunk the documents into text units. The GraphRAG documentation gives a default of 1,200 tokens; the paper's experiments used 600-token chunks with 100 tokens of overlap. The paper notes the trade-off: longer chunks mean fewer LLM calls but worse recall of content that appears early in a chunk.
- Extract entities and relations from each chunk. The prompt asks for entities with a name, a type from a list you choose (person, organization, product, place, event) and a short description, and for relations between pairs of them, each with a description and a strength.
- Glean. The paper runs extra rounds in which the model is asked whether it missed entities and, if so, told that many were missed and asked to continue, up to a set number of rounds. This raises recall at the price of more calls.
- Optionally extract claims: dated, factual statements about entities, which the GraphRAG documentation calls covariates and leaves off by default.
- Merge and summarize. The same entity extracted from many chunks has many descriptions; an LLM condenses each list into one description, and the same happens for relations.
- Detect communities, write a report per community, and embed entity descriptions, text units and reports for later lookup.
Keep provenance from the first step. Every entity and relation should point back to the chunks it came from, so an answer can cite source text rather than an LLM's paraphrase, and so a bad extraction can be traced and fixed. Store the entity type with the entity: "Mercury" the planet and "Mercury" the company should never merge, and the type is the cheapest signal that keeps them apart.
Extraction quality caps everything downstream. If the model misses a relation, no traversal will find it; if it invents one, retrieval will cite it confidently. Ask for structured output against a schema so parsing never fails, keep the relation vocabulary small enough that the same fact is written the same way, and sample extractions by hand early, before indexing a large corpus. Chunking choices matter here as much as in vector RAG; see chunking strategies for RAG.
Entity resolution: the step that makes hops possible
An LLM extracting chunk by chunk will write "Northwind Group" in one chunk, "Northwind Grp." in another and "Northwind" in a third. If those stay three nodes, the graph is three disconnected fragments and a two-hop question fails at the first hop. Entity resolution decides which mentions are the same real-world thing.
The GraphRAG paper and documentation take the simple route: entities with the same title and type are merged, and their descriptions are summarized together. The paper says its analysis used exact string matching, notes that softer matching needs only small changes, and argues the method is fairly resilient to duplicates because variants usually land in the same community and get summarized together. That holds for global summaries. A traversal is less forgiving: it needs one node to walk from, and every unmerged spelling is a dead end. Stronger options, roughly in order of effort:
- Normalize before matching: case, whitespace, punctuation, legal suffixes such as "Inc." and "Ltd." where your domain allows it.
- Keep an alias table: canonical name, aliases and identifiers such as a domain name, ticker or internal ID. Seed it from structured data you already have; that beats any model.
- Generate candidate pairs cheaply (same type, similar embedding of name plus description, shared neighbors), then ask an LLM, or a person for high-stakes data, to confirm each candidate merge.
- Record merges as data, with the reason, so a wrong merge can be undone without re-indexing the corpus.
Wrong merges are worse than missed ones. Two different people with the same name, merged, produce a fluent and false biography. Prefer precision: merge only on strong evidence, and let the type and the neighborhood veto a merge that string similarity suggests.
The small example below builds a graph from triples, as an extractor might return them, resolves one alias, and answers two-hop questions by walking edges. It uses only the Python standard library, so it runs anywhere; a library such as networkx gives you the same structure with more algorithms attached.
from collections import defaultdict
# Triples as an LLM extractor might return them, one list per chunk
triples = [
('Acme Robotics', 'ACQUIRED_BY', 'Northwind Group'),
('Northwind Group', 'HEADQUARTERED_IN', 'Rotterdam'),
('Dana Reyes', 'CEO_OF', 'Northwind Grp.'),
('Acme Robotics', 'MAKES', 'warehouse arms'),
('Lumen Labs', 'ACQUIRED_BY', 'Northwind Group'),
('Lumen Labs', 'HEADQUARTERED_IN', 'Lisbon'),
]
# Entity resolution: map surface forms to one canonical name
aliases = {'northwind grp.': 'Northwind Group'}
def canon(name):
return aliases.get(name.lower(), name)
out_edges = defaultdict(list) # subject -> [(relation, object)]
in_edges = defaultdict(list) # object -> [(relation, subject)]
for s, r, o in triples:
s, o = canon(s), canon(o)
out_edges[s].append((r, o))
in_edges[o].append((r, s))
def hop(entity, relation):
return [o for r, o in out_edges[entity] if r == relation]
# Two hops: Acme Robotics -ACQUIRED_BY-> ? -HEADQUARTERED_IN-> ?
for parent in hop('Acme Robotics', 'ACQUIRED_BY'):
for city in hop(parent, 'HEADQUARTERED_IN'):
print(f'Acme Robotics -> {parent} -> {city}')
# Two hops the other way: who runs the company that bought Lumen Labs?
for parent in hop('Lumen Labs', 'ACQUIRED_BY'):
ceos = [s for r, s in in_edges[parent] if r == 'CEO_OF']
print(f'Lumen Labs -> {parent} <- CEO {ceos}')
# Everything within two hops of Acme Robotics, ignoring direction
frontier, seen = {'Acme Robotics'}, {'Acme Robotics': 0}
for depth in (1, 2):
nxt = set()
for e in frontier:
for _, n in out_edges[e] + in_edges[e]:
if n not in seen:
seen[n] = depth
nxt.add(n)
frontier = nxt
print(sorted(seen.items(), key=lambda kv: (kv[1], kv[0])))
# Acme Robotics -> Northwind Group -> Rotterdam
# Lumen Labs -> Northwind Group <- CEO ['Dana Reyes']
# [('Acme Robotics', 0), ('Northwind Group', 1), ('warehouse arms', 1), ('Dana Reyes', 2), ('Lumen Labs', 2), ('Rotterdam', 2)]The comment lines at the end are the real output. The same script with the alias table emptied finds the buyer's city but returns an empty list for the CEO, and Dana Reyes disappears from the two-hop neighborhood, because the CEO edge hangs off a separate "Northwind Grp." node. One missed merge, one wrong answer, and nothing in the output says so.
Community detection and community summaries
Global questions need something corpus-wide to read. GraphRAG gets it by partitioning the graph into communities, groups of entities more densely connected to each other than to the rest, and having an LLM write a report for each community: what the entities are, how they relate, and the main claims about them.
The paper uses the Leiden algorithm, applied hierarchically: it finds communities, then recursively finds sub-communities inside each one until the leaves cannot be split further. Every level is a complete partition, so each entity belongs to exactly one community per level. Leiden comes from Traag, Waltman and van Eck, who showed that the widely used Louvain method can produce badly connected and even disconnected communities, reporting up to 25 percent badly connected and up to 16 percent disconnected in their experiments. Leiden guarantees connected communities and, the authors report, runs faster than Louvain.
Reports are written bottom-up. For a leaf community, the paper adds material in priority order until the token limit: edges ranked by the combined degree of their two endpoints, each with the descriptions of both entities, the edge itself and related claims. For a higher-level community whose material does not fit, it swaps in the shorter reports of its sub-communities until the content fits. The paper names the levels C0 (root, fewest and broadest reports) to C3 (most numerous and most detailed).
This is where most of the indexing work and most of the value of global search sit. The reports are precomputed answers to "what is going on in this part of the corpus", and the choice of level at query time is a choice between breadth and detail.
Local search and global search
The GraphRAG documentation describes two main query modes, and they solve the two failure cases from the first section.
Local search is for questions about specific entities. It embeds the question, finds entities whose descriptions are similar, and uses them as entry points into the graph. From there it gathers connected entities and relations, claims, the community reports those entities belong to, and the original text units linked to them, then ranks and filters the candidates to fit a context window of fixed size. It is vector retrieval used to choose a starting point, followed by graph expansion to collect what similarity would miss.
Global search is for questions about the whole dataset. It is a map-reduce over community reports at a chosen level. In the paper's version, the reports are shuffled and split into chunks of a fixed token size; in the map step, each chunk produces a partial answer with a helpfulness score from 0 to 100, and answers scored 0 are dropped. In the reduce step, the partial answers are sorted by score and added to a final context until it is full, and the model writes the global answer from that. The documentation notes that lower levels, with more detailed reports, tend to give more thorough answers at the price of more time and more LLM calls.
| Aspect | Vector RAG | GraphRAG local search | GraphRAG global search |
|---|---|---|---|
| Best at | Questions answered by one or a few similar passages | Questions about specific entities and their connections | Themes, trends and summaries across the corpus |
| Index | Chunk embeddings, optionally a keyword index | Entities, relations, claims, text units and their embeddings | Hierarchy of community reports |
| Query work | One embedding and a nearest-neighbor lookup | Entity lookup, graph expansion, ranking into one context | One LLM call per batch of reports, then a reduce call |
| Multi-hop | Only if every passage ranks highly on its own | Follows relations from the matched entities | Indirectly, through summaries |
| Indexing effort | Embed every chunk once | LLM extraction and summarization over every chunk | Extraction plus a report per community, per level |
| Freshness | Add or replace chunks any time | New chunks need extraction and resolution | New data can change communities and their reports |
| Failure mode | Misses facts that do not look like the question | Garbage in from bad extraction or bad merges | Generic, smoothed answers; loses rare details |
On results, the paper reports head-to-head comparisons judged by an LLM on comprehensiveness, diversity and empowerment, with directness as a control criterion, over two corpora of roughly a million tokens each. On the podcast transcripts, the authors report GraphRAG win rates against vector RAG of 72 to 83 percent on comprehensiveness and 75 to 82 percent on diversity, across the GraphRAG conditions they tested. They also report that answering from root-level summaries took over 97 percent fewer tokens than map-reducing over the source text, while still beating vector RAG on both criteria. These are win rates on global sensemaking questions; they say nothing about local fact questions, where vector RAG is the natural baseline.
Lighter variants: LightRAG and friends
Full GraphRAG indexing is heavy, and many teams want the multi-hop benefit without the community hierarchy. Several lighter designs exist.
LightRAG, from Guo et al., keeps the LLM-extracted entity and relation graph, combines it with vector representations, and uses dual-level retrieval: low-level retrieval for specific entities and their relations, and high-level retrieval for broader topics. Its authors also describe an incremental update algorithm that adds new data to the graph without rebuilding the whole index, which matters for corpora that change. They report better retrieval accuracy and response times than the approaches they compare against; as with any paper, check the benchmark against your own questions.
- Cheaper extraction. The GraphRAG documentation describes a FastGraphRAG option that uses classic NLP to extract entities and relations instead of an LLM, which is faster and lower in fidelity.
- No communities. Build only the entity graph and use it to expand vector hits by one or two hops. This targets multi-hop questions and skips global search entirely.
- Graph from metadata. If your documents already carry structure (authors, products, tickets, links, foreign keys), build the graph from that and skip LLM extraction for those relations.
- Summaries on demand. Instead of writing every community report at index time, summarize only the communities a query touches, and keep the results for reuse.
The common thread is that the graph is a retrieval index, not a product in itself. Build the cheapest graph that answers the questions your users actually ask, measured on those questions.
Storing and querying the graph: graph database or Postgres
A retrieval graph is usually modest next to the corpus: entities, relations with descriptions, links to chunks, and embeddings. You can store it in a graph database or in a relational database you already run.
Graph databases make traversal the native operation. In Cypher, a variable number of hops is written as a quantified relationship. The Cypher manual warns that quantified patterns can match very large numbers of paths and slow a query down, and recommends a finite upper bound, a more specific pattern (labels, direction) and inline predicates that prune paths early. The snippet below follows the manual's syntax; it is illustrative and was not run here.
// Two outgoing hops from one entity, written as a quantified relationship
MATCH (a:Entity {name: 'Acme Robotics'})-[:RELATED]->{1,2}(b:Entity)
RETURN DISTINCT b.name
// The same fixed two-hop question as the SQL join above
MATCH (:Company {name: 'Lumen Labs'})-[:ACQUIRED_BY]->(buyer)<-[:CEO_OF]-(ceo)
RETURN buyer.name, ceo.nameIn PostgreSQL, the same graph is two tables, an entity table and an edge table with indexes on both ends, and a traversal is a recursive common table expression. PostgreSQL evaluates the non-recursive term once, then repeats the recursive term against the rows produced by the previous step until no new rows appear. A depth column with a limit keeps the walk bounded, which also stops it on cycles; for unbounded walks, PostgreSQL 14 added a CYCLE clause that tracks visited rows. The example below ran unchanged on a local PostgreSQL 14 and on SQLite 3.54, and the comments show its real output.
CREATE TABLE entities (
id integer PRIMARY KEY,
name text UNIQUE
);
CREATE TABLE edges (
src integer REFERENCES entities (id),
relation text,
dst integer REFERENCES entities (id),
PRIMARY KEY (src, relation, dst) -- also the index for outgoing hops
);
CREATE INDEX edges_dst ON edges (dst); -- for incoming hops
INSERT INTO entities VALUES
(1, 'Acme Robotics'), (2, 'Northwind Group'), (3, 'Rotterdam'),
(4, 'Dana Reyes'), (5, 'Lumen Labs'), (6, 'Lisbon');
INSERT INTO edges VALUES
(1, 'ACQUIRED_BY', 2), (2, 'HEADQUARTERED_IN', 3), (4, 'CEO_OF', 2),
(5, 'ACQUIRED_BY', 2), (5, 'HEADQUARTERED_IN', 6);
-- Everything reachable from Acme Robotics in at most two outgoing hops
WITH RECURSIVE walk (id, depth, path) AS (
SELECT id, 0, name FROM entities WHERE name = 'Acme Robotics'
UNION ALL
SELECT e.dst, w.depth + 1, w.path || ' -' || e.relation || '-> ' || n.name
FROM walk w
JOIN edges e ON e.src = w.id
JOIN entities n ON n.id = e.dst
WHERE w.depth < 2 -- the hop limit also stops cycles
)
SELECT depth, path FROM walk WHERE depth > 0 ORDER BY depth, path;
-- 1 | Acme Robotics -ACQUIRED_BY-> Northwind Group
-- 2 | Acme Robotics -ACQUIRED_BY-> Northwind Group -HEADQUARTERED_IN-> Rotterdam
-- A fixed two-hop question is just two joins: who runs the buyer of Lumen Labs?
SELECT buyer.name AS buyer, ceo.name AS ceo
FROM entities t
JOIN edges a ON a.src = t.id AND a.relation = 'ACQUIRED_BY'
JOIN entities buyer ON buyer.id = a.dst
JOIN edges c ON c.dst = a.dst AND c.relation = 'CEO_OF'
JOIN entities ceo ON ceo.id = c.src
WHERE t.name = 'Lumen Labs';
-- Northwind Group | Dana ReyesFor retrieval graphs, the relational route is often enough. Queries are shallow, one to three hops from a handful of entry points; the edge table is indexed on both ends; and keeping entities, chunks and embeddings in one database means one transaction, one backup and one access-control model. A graph database earns its place when traversals get deep or path-heavy (shortest paths, many-hop patterns), when graph algorithms run often enough to need native support, or when people other than the retrieval pipeline explore the graph directly. Community detection itself usually runs offline in a library, whichever store you choose; the paper's implementation used the graspologic library.
Indexing effort versus benefit
Vector indexing costs one embedding call per chunk. GraphRAG indexing costs, roughly, one extraction call per chunk times the number of gleaning rounds, one summarization call per entity and relation with several descriptions, one report per community per level, and embeddings on top. That is many more tokens and much more wall-clock time than embedding, and it repeats when the corpus changes: new chunks need extraction and resolution, and new relations can move entities between communities, which makes their reports stale.
Questions worth answering before committing to it:
- What share of real user questions are multi-hop or global? Pull a sample of logged questions and label them. If almost all are local fact lookups, improve hybrid search and reranking first.
- How fast does the corpus change? A stable archive (research reports, transcripts, case files) suits a heavy index. A help center edited many times a day suits a lighter one, or incremental updates.
- Is there existing structure? Relations you already store in databases are free, exact edges. Extract with an LLM only what lives in prose.
- Can you afford stale summaries? Global answers from reports written before last month's documents arrived will not mention them. Track when each report was built and from which chunks.
- How will you check the graph? An unreviewed LLM-built graph is a large, confident, unaudited dataset. Budget time for sampling and fixing it.
A sensible path is incremental: start with hybrid vector RAG and an evaluation set; add an entity graph for one-hop and two-hop expansion when the evaluation shows multi-hop failures; add communities and global search only when users ask corpus-wide questions and the baseline visibly fails them.
Evaluating GraphRAG
Evaluate a graph-based system the way you evaluate any RAG system, with one addition: the graph itself is a component with its own errors. How to evaluate RAG covers retrieval and answer metrics in general; the GraphRAG-specific parts are below.
- Build a question set by type: local facts, multi-hop questions with known paths, and global questions. Report every metric per type, because a gain on global questions can hide a loss on local ones.
- Keep a vector or hybrid RAG baseline on the same corpus and the same model, and compare against it on every change.
- For multi-hop questions, check the path, not only the answer: did retrieval reach the entities and chunks on the gold path? This separates a missing edge from a model that ignored good context.
- For global questions there is no single right answer. The GraphRAG paper used pairwise comparisons judged by an LLM on comprehensiveness, diversity and empowerment, with directness as a control, repeated several times and averaged. It also checked those judgments with a claim-based measure: extract the factual claims in each answer and count and cluster them.
- Audit the graph: sample extracted relations and score their precision against the source chunks, count duplicate entities that should have merged and merges that should not have happened, and track how many entities have no relations.
- Measure the work: indexing tokens and time per document, query latency, and LLM calls per global query. Global search over a detailed level can be many calls per question.
Zheng et al., studying LLMs as judges, describe position, verbosity and self-enhancement biases. Verbosity matters most here, because global search produces long, detailed answers. Swap the order of the two answers between runs, include a directness criterion as the paper did, and calibrate the judge against a small set of human ratings before trusting a win rate.
If you are building retrieval over documents where the answers span many sources, see our AI agent development service: the code lives in your GitHub from day one, AI-assisted work is reviewed by an engineer, and the founders are on the calls.
Sources
Checked when this post was written.
- Edge et al., From Local to Global: A Graph RAG Approach to Query-Focused Summarization (arXiv, 2024)
- Microsoft GraphRAG documentation: Dataflow (indexing)
- Microsoft GraphRAG documentation: Local Search
- Microsoft GraphRAG documentation: Global Search
- Traag, Waltman and van Eck, From Louvain to Leiden: guaranteeing well-connected communities (arXiv, 2018)
- Guo et al., LightRAG: Simple and Fast Retrieval-Augmented Generation (arXiv, 2024)
- Yang et al., HotpotQA: A Dataset for Diverse, Explainable Multi-hop Question Answering (arXiv, 2018)
- PostgreSQL documentation: WITH Queries (Common Table Expressions)
- Zheng et al., Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena (arXiv, 2023)
- Neo4j Cypher Manual: Variable-length patterns