GraphRAG: answering from a knowledge graph of entities and communities

GraphRAG turns documents into a graph of entities and relationships, groups them into summarised communities, and answers from that structure. Use it for questions about themes and connections across a whole collection.

GraphRAG in 60 seconds

  • What: a model extracts entities and relationships from documents into a graph, groups related entities into communities, and writes a summary for each community.
  • Two query modes: global questions combine community summaries; local questions start at named entities and read their neighbours.
  • Why: top-k chunk search struggles with 'what are the main themes across everything?' because no single chunk holds the answer.
  • Cost: indexing is expensive, because a model reads the whole corpus and writes many summaries.
  • Risk: quality depends on extraction, so a missed or merged entity quietly weakens every answer that touches it.

Where this type fits

GraphRAG belongs to the structure or media family, together with multimodal, modular and vectorless RAG. Its distinguishing move is to add structure at indexing time, so that query time can use relationships instead of only text similarity. See the overview of RAG types for how it compares with the single-pass and loop-based types.

The problem it solves

Standard RAG answers a question by finding a handful of chunks that look like it. This works for 'What is the notice period in the supplier contract?' because one chunk holds the answer. It fails for 'What are the main risks that appear across all our supplier contracts?' No chunk says that. The answer is spread over hundreds of chunks, and any top-k search returns only a few of them, usually the ones that use the word 'risk' most loudly.

A second weakness is connection. 'Which suppliers share a subcontractor with the one that failed an audit?' needs a path from supplier to subcontractor to other suppliers. Similarity search finds passages near the words, but it has no notion of a path. A human analyst would draw the relationships on paper first.

Think of a detective's board with photographs and string. Reading every witness statement in order is slow, and no one statement reveals the pattern. Pinning names to the board and linking them shows who is connected to whom, and a short note per cluster lets you see the big picture quickly. GraphRAG builds the board once, in advance, so that questions can be answered from it.

How it works

The best-known description is Edge et al., 2024, From Local to Global: A Graph RAG Approach to Query-Focused Summarization. The steps below follow its outline in plain terms. Other systems use the name for different graph-based designs, so check which one a product means.

  • Chunk the documents: split the corpus into manageable pieces, as in any RAG system.
  • Extract entities and relationships: a model reads each chunk and lists the named things (people, organisations, places, products) and how they relate, with a short description of each.
  • Build the graph: merge repeated mentions of the same entity into one node and join nodes by their relationships.
  • Detect communities: a graph algorithm groups closely connected entities into communities, often at several levels from small to large.
  • Summarise each community: a model writes a report for each community covering its main entities, relationships and claims. These are computed once, before any question arrives.
  • Answer global questions: the model reads relevant community summaries, writes partial answers, then combines them into one answer.
  • Answer local questions: the system finds entities named in the question, reads their descriptions, neighbours and linked source chunks, and answers from that.
Specific questions walk the graph; broad questions combine community summaries.

The two query modes suit different questions. Global mode asks the whole collection a broad question and uses the community summaries as a compressed view of the corpus. Because the summaries already exist, the model reads a few thousand tokens of reports instead of the entire corpus. Local mode begins at specific entities, so it is closer to ordinary retrieval, except that it can step along relationships to bring in related material that shares no words with the question.

Communities are the clever part. A community is a group of entities that link to each other more than to the rest of the graph, for example a supplier, its subcontractors and the contracts that join them. Writing one summary per community turns a large, tangled corpus into a hierarchy of readable briefs. Higher levels cover broad themes, and lower levels cover detail.

A worked example

Acme Foods keeps 400 supplier contracts and audit reports. A procurement lead asks two questions, one global and one local.

  • Extraction: reading a chunk from contract 112, the model returns entities 'Northwind Packaging' (supplier), 'Delta Cartons' (subcontractor), 'Audit 2025-07' (event) and the relationships 'Northwind subcontracts to Delta' and 'Audit 2025-07 found late delivery at Delta'.
  • Merging: 'Delta Cartons', 'Delta Cartons Ltd' and 'Delta' in other contracts are resolved to one node. This step decides how good the graph is.
  • Communities: the algorithm groups Northwind, Delta, two other packaging suppliers and their audits into 'Packaging supply chain'. Another community covers 'Cold storage logistics'.
  • Summaries: the packaging report says: 'Three suppliers depend on Delta Cartons. Late delivery is the most frequent finding. Two contracts have no penalty clause.'
  • Global question: 'What are the main risks across our supplier base?' The system reads the community reports, each model call produces a partial answer with a helpfulness score, and a final call merges the highest scoring partials into themes: concentration on single subcontractors, late delivery, missing penalty clauses.
  • Local question: 'Which suppliers share a subcontractor with the one that failed the July audit?' The system finds 'Audit 2025-07', follows to Delta Cartons, then follows 'subcontracted by' edges to Northwind and two others, and reads the linked contract chunks to answer with citations.
A fragment of the extracted graph (illustrative) (json)
{
  'entities': [
    {'id': 'e1', 'name': 'Northwind Packaging', 'type': 'supplier'},
    {'id': 'e2', 'name': 'Delta Cartons', 'type': 'subcontractor'},
    {'id': 'e3', 'name': 'Audit 2025-07', 'type': 'event'}
  ],
  'relations': [
    {'from': 'e1', 'to': 'e2', 'type': 'subcontracts_to', 'source_chunk': 'c-112-04'},
    {'from': 'e3', 'to': 'e2', 'type': 'found_late_delivery_at', 'source_chunk': 'c-208-11'}
  ],
  'communities': [{'id': 'k1', 'level': 1, 'members': ['e1', 'e2', 'e3'], 'summary': 'Packaging supply chain ...'}]
}

Building it

The sketch below shows the indexing pipeline and both query modes at a small scale. The extraction call, graph library and community algorithm are placeholders. Notice that every graph item keeps a pointer back to its source chunk, because citations and debugging both depend on it.

Indexing and query modes for a graph-based RAG (illustrative) (python)
# Placeholders: llm.generate_json, llm.generate, graph (a graph store), detect_communities,
# vector_store and embed stand in for real components.

def build_index(chunks):
    for chunk in chunks:
        # Ask for entities and relations in a fixed JSON shape so parsing is predictable.
        found = llm.generate_json(extract_prompt(chunk.text))
        for ent in found['entities']:
            node = graph.upsert_node(normalise(ent['name']), ent['type'], ent['description'])
            node.sources.add(chunk.id)   # keep provenance for citations and debugging
        for rel in found['relations']:
            graph.add_edge(normalise(rel['from']), normalise(rel['to']), rel['type'], chunk.id)
    # Communities are computed once, offline, at several levels of size.
    for level, community in detect_communities(graph, levels=2):
        report = llm.generate(community_prompt(graph.describe(community)))
        graph.save_report(community.id, level, report.text)

def answer_global(question, level=1, max_reports=20):
    reports = graph.reports(level)
    # Rank reports so a huge graph does not blow the context or the cost budget.
    ranked = sorted(reports, key=lambda r: similarity(question, r), reverse=True)[:max_reports]
    partials = [llm.generate(partial_prompt(question, r)) for r in ranked]
    partials = [p for p in partials if p.score > 0]   # drop reports that did not help
    return llm.generate(combine_prompt(question, partials))

def answer_local(question, hops=1, max_chunks=12):
    names = llm.generate_json(entity_prompt(question))['entities']
    seeds = [graph.find(normalise(n)) for n in names if graph.find(normalise(n))]
    context = graph.neighbourhood(seeds, hops=hops)   # keep hops small: graphs explode quickly
    chunk_ids = context.chunk_ids()[:max_chunks]
    chunks = vector_store.fetch(chunk_ids)
    return llm.generate(local_prompt(question, context.facts(), chunks))
Entity name normalisation before merging nodes (illustrative) (python)
import re

SUFFIXES = re.compile(r'\b(ltd|limited|inc|gmbh|llc|plc)\b\.?', re.I)

def normalise(name):
    # Cheap rules catch most duplicates; send the rest to a model or a person for review.
    cleaned = SUFFIXES.sub('', name).strip().lower()
    return re.sub(r'\s+', ' ', cleaned)

Design decisions

  • Storage: keep the graph, the community reports and the source chunks in stores that suit each: a graph or relational store for nodes and edges, a document store for reports, and a vector index for chunks and entity descriptions. Keep ids consistent across them.
  • Indexing cost: run extraction as a batch job, and cache the model's output per chunk hash. A re-index then repeats work only for changed chunks. Estimate cost by sampling before running on the whole corpus.
  • Updates and versioning: decide how new documents enter. Incremental updates are cheaper but can leave stale community reports. A common default is incremental extraction with a scheduled community rebuild, and a version tag on every report.
  • Entity resolution: invest in merging duplicates early. Combine rule-based normalisation with a review queue for uncertain pairs, since a wrong merge is harder to find than a missed one.
  • Access control: a community report mixes facts from many documents, so a user who can see the report may learn facts from a document they cannot open. Build communities per permission group, or filter reports by the lowest common access. See security.
  • Query latency: global mode makes many model calls, so cap the number of reports and run the partial answers in parallel. Local mode is cheaper, so route to it whenever a question names specific entities.
  • Failure handling: if extraction fails for a chunk, record it and continue. The index should report coverage, for example the share of chunks that produced valid entities.

Measuring it

  • Extraction quality: on a labelled sample of chunks, compute precision and recall of entities and relations against a human list. This bounds everything downstream.
  • Entity resolution accuracy: on a sample of known duplicate and non-duplicate pairs, count wrong merges and missed merges separately.
  • Global answer quality: pairwise comparison of answers from GraphRAG and a baseline on broad questions, judged by people or a grader model on comprehensiveness and diversity of points. The paper uses this style of comparison, and results depend on the dataset.
  • Local answer correctness: exact or graded correctness on entity-centred questions, with the share of claims supported by cited chunks.
  • Cost and freshness: tokens spent on indexing per thousand chunks, query cost in global mode, and the age of the oldest community report.
Entity extraction precision and recall on a labelled sample (illustrative) (python)
def entity_scores(predicted, gold):
    # predicted and gold are sets of normalised entity names for the same chunks.
    tp = len(predicted & gold)
    precision = tp / len(predicted) if predicted else 0.0
    recall = tp / len(gold) if gold else 0.0
    return {'precision': precision, 'recall': recall}

When to use it, and when not to

SituationUse this type?Why
Broad questions about themes across a large collectionYesCommunity summaries give a compressed view that top-k chunk search cannot.
Questions about how people, companies or items are connectedYesThe graph holds relationships that similarity search ignores.
Narrow factual lookups in a small corpusNoSimple RAG answers these cheaply, and the graph adds cost without benefit.
Corpus that changes every hourOnly with careRe-extraction and community rebuilds are expensive, and reports go stale.
Documents with weak entity structure, such as casual chat logsNoExtraction will be noisy and the graph will mislead.
Investigations, due diligence and research synthesisYesThe questions are about patterns and links, which is the graph's strength.

Trade-offs

DimensionEffectWhat to do about it
QualityStronger on broad and relational questions, no better on simple lookupsRoute by question type and keep a chunk-based path for lookups.
LatencyLocal mode is fast; global mode makes many calls and can take many secondsCap reports, parallelise partial answers and precompute common global answers.
CostHeavy indexing spend up front, and again on rebuildsCache extraction per chunk, sample before scaling and rebuild on a schedule.
ComplexityExtraction, resolution, community detection and several stores to runStart with a small corpus and a measured baseline before committing.
Failure modesMissed or merged entities, stale summaries, summaries that blend permissionsReview samples, version reports and split communities by access group.

Vectorless RAG also adds structure, but it uses the document's own outline, such as headings, instead of a graph of entities. It suits one long, well-organised document, whereas GraphRAG suits many documents that mention the same things. Advanced RAG improves chunk retrieval with rewriting, hybrid search and reranking. It stays chunk-based, so it still struggles with whole-corpus questions.

Agentic RAG could use a graph as one of its tools, choosing local graph lookups for entity questions and vector search for others. Modular RAG describes how to make the graph a swappable module in a larger pipeline.

What this means for your role

Common mistakes

Further reading

GraphRAG pays upfront to give a model a map of the collection. It repays that cost on broad and relational questions, and it needs honest measurement to show whether your questions are of that kind.

Search topics

↑↓ to move · Enter to open · Esc to close