Free, open courseware in graph theory and its applications

learngraphtheory.org Algorithms · Networks · Graph AI · Optimization
Graph AI

What Is GraphRAG? Knowledge Graphs for Retrieval-Augmented Generation

GraphRAG gives a large language model a map of your documents instead of a pile of passages. This guide explains how the knowledge graph is built, which graph algorithms do the work, and when the extra cost pays off.

19 Min Read Updated: December 2026 Intermediate Level
A whiteboard where highlighted passages from five printed documents are linked by arrows to a hand-drawn knowledge graph, its nodes circled into three coloured communities, each with a summary note
Mohammed Islam Hadjoudj
Mohammed Islam Hadjoudj
Scientific Software Developer and Operations Research Engineer
MSc in Operations Research · BSc in Mathematics

1. What Is GraphRAG?

Ask a chatbot about your own documents and it will usually answer through retrieval-augmented generation (RAG). The system searches a document store for passages that resemble the question, pastes the best matches into the prompt, and lets a large language model (LLM) write the answer from them. This works remarkably well when the answer sits in one or two passages. It struggles when the answer is spread across many documents, or when the question is about the collection as a whole.

GraphRAG is the family of techniques that addresses this by putting a graph between the documents and the model. Instead of treating a corpus as a pile of independent text chunks, GraphRAG first extracts the entities the text talks about (people, organisations, products, places, concepts) and the relationships between them, and stores them as a knowledge graph. At question time the system navigates that graph. It follows edges to connect facts that live in different documents, and it uses the graph’s community structure to summarise themes that no single passage states.

The name took off in 2024, when Microsoft Research published From Local to Global: A Graph RAG Approach to Query-Focused Summarization (Edge et al.) and released an open-source implementation called graphrag. Today the term covers both that specific pipeline and a broader idea: any RAG system in which a graph, rather than a flat list of passages, organises what the model is allowed to read. Graph databases, LLM frameworks and cloud platforms all ship GraphRAG features, which makes it one of the most practical places where classic graph theory meets modern AI.

In one sentence: GraphRAG builds a knowledge graph from your documents with an LLM, groups it into communities with a graph algorithm, and answers questions by traversing the graph and reading community summaries, not only by matching similar text.

This guide explains GraphRAG from the ground up: why vector search alone falls short, what a knowledge graph is, how the indexing and query pipelines work, which graph algorithms do the heavy lifting, how to build a system yourself, and when the extra cost is worth paying.

2. Where Plain Vector RAG Falls Short

To see what the graph adds, start with how standard RAG, often called vector RAG or naive RAG, retrieves text. Documents are split into chunks of a few hundred tokens. Each chunk is turned into an embedding, a vector of numbers that captures its meaning, and stored in a vector database. A question is embedded the same way, and the k chunks whose vectors are closest to it, usually by cosine similarity, are placed in the prompt.

Similarity search is fast, cheap and easy to keep up to date, and for many questions it is all you need. Its weaknesses all come from one hidden assumption: that the passage containing the answer looks like the question. Four kinds of questions break that assumption.

None of this makes vector search obsolete. Most production GraphRAG systems still use embeddings, for example to find the entities a question mentions. The graph is an additional index, one that stores the connections between facts rather than only the facts themselves.

3. Knowledge Graphs in Five Minutes

A knowledge graph is a graph whose nodes are entities and whose edges are typed relationships between them. In graph-theory terms it is a labelled, directed multigraph: an edge from Corvo Alloys to Halden Port labelled SHIPS_THROUGH is different from an edge labelled OWNS between the same two nodes, and both can exist at once. If those terms are new, our guides to directed vs undirected graphs and simple graphs vs multigraphs cover them.

The smallest unit of a knowledge graph is a triple of the form (head, relation, tail), for example (Brisa Electronics, MAKES, C7 controller board). A collection of triples is already a graph: every distinct head or tail becomes a node and every triple becomes an edge. Two data models dominate in practice.

What makes a knowledge graph useful to an LLM is that the hard work of reading is done once. The model reads every document at indexing time and writes down who did what to whom. From then on, questions can be answered by traversing explicit structure instead of re-reading prose. Traversal is exactly what graph algorithms are good at: breadth-first search finds everything within k hops, shortest-path algorithms connect two entities, centrality measures rank what matters, and community detection groups related entities into topics.

ConceptIn the textIn the knowledge graph
Entity“Brisa Electronics, a contract manufacturer”A node with the type Organization
Relationship“assembles the C7 controller board”A directed edge labelled MAKES
Attribute“founded in 1998”A property on the node
TopicMany documents about electronics suppliersA community of densely linked nodes
EvidenceThe sentence itselfA link from the node or edge to its source text

4. The Indexing Pipeline, Step by Step

GraphRAG does most of its work before anyone asks a question. The indexing pipeline turns raw documents into a graph plus a set of summaries. Microsoft’s reference implementation runs six stages, and most other systems use some subset of them.

The GraphRAG indexing pipeline: documents are split into text units, an LLM extracts entities and relationships, these merge into a knowledge graph, the Leiden algorithm groups the graph into communities, and the LLM writes a report for every community.
Figure 1. The GraphRAG indexing pipeline. Every later answer is built from the graph, the communities and the reports produced here.

Step 1: Split documents into text units

Documents are cut into chunks, called text units, of a few hundred tokens with some overlap. Chunk size matters more here than in vector RAG, because every chunk is read by an LLM for extraction. In the original paper, 600-token chunks yielded almost twice as many entity references as 2,400-token chunks: long inputs make the model skim.

Step 2: Extract entities and relationships with an LLM

Each text unit is sent to an LLM with an extraction prompt: list every entity with its name, type and a short description, and every relationship between two entities with a description and a strength score. Optional gleaning rounds then ask the model whether it missed anything and add what it finds. Some pipelines also extract claims, factual statements with dates and a status, linked to the entities they concern. A typical extraction result looks like this:

{
  "entities": [
    {"name": "Brisa Electronics", "type": "ORGANIZATION",
     "description": "Contract manufacturer that assembles the C7 board"},
    {"name": "C7 controller board", "type": "PRODUCT",
     "description": "Control board used in industrial pumps"}
  ],
  "relationships": [
    {"source": "Brisa Electronics", "target": "C7 controller board",
     "description": "Brisa Electronics assembles the C7 board", "strength": 9}
  ]
}

Step 3: Merge and resolve entities

The same entity appears in many chunks, so the per-chunk results are merged. Nodes with the same name and type become one node, their descriptions are combined and summarised by the LLM into a single description, and repeated relationships between the same pair are merged into one weighted edge. Entity resolution, deciding that “C7 board” and “C7 controller board” are the same thing, is one of the hardest and most underrated parts of the process. Simple pipelines rely on exact names, while better ones add embedding similarity, string distance and domain rules.

Step 4: Detect communities

The resulting graph is partitioned into communities: groups of entities that are more densely connected to each other than to the rest of the graph. Microsoft’s pipeline uses the hierarchical Leiden algorithm. It partitions the graph, then partitions each community again, and so on. The result is a tree of levels, from a few broad communities at the top to many small, specific ones at the bottom.

Step 5: Summarise every community

For each community at each level, the LLM writes a community report: a title, a summary of the key entities and relationships, a list of findings, and an importance rating. Bottom-level communities are summarised from their entity and relationship descriptions. Higher-level communities are summarised from the reports of their sub-communities whenever the raw material would not fit in the context window. These reports are what make questions about the whole corpus answerable.

Step 6: Embed and store

Finally, entity descriptions, text units and community reports are embedded for vector search, and everything is written to storage: nodes, edges, communities, reports, embeddings, and the links back to the source text. The reference implementation writes Parquet files, while production systems often load the result into a graph database.

The outcome is a layered index. At the bottom are the original text units. Above them sits a graph of entities and relationships, each traceable to the text it came from. Above that sits a hierarchy of communities with natural-language summaries. A question can enter at whichever layer suits it.

5. The Graph Algorithms Inside GraphRAG

Large language models get the headlines, but much of GraphRAG’s power comes from classic graph algorithms. Most of them can be run step by step in our visualizer.

Community detection: Leiden and Louvain

Community detection is the heart of global search. Both the Louvain algorithm and its successor Leiden greedily maximise modularity, a score that compares the number of edges inside communities with the number you would expect if the edges were rewired at random while every node kept its degree:

Q = (1 / 2m) Σᵢⱼ [ Aᵢⱼ − kᵢ kⱼ / 2m ] δ(cᵢ, cⱼ)

Here A is the adjacency matrix, kᵢ is the degree of node i, m is the number of edges, and δ(cᵢ, cⱼ) equals 1 when the two nodes share a community and 0 otherwise. Louvain repeatedly moves single nodes to the neighbouring community that raises Q the most, then collapses each community into one super-node and repeats. Leiden (Traag, Waltman and van Eck, 2019) adds a refinement phase that guarantees every community is internally connected. This fixes a known Louvain flaw in which a community can fall apart into disconnected pieces.

For GraphRAG that guarantee matters. A community report written about a disconnected group of entities would mix unrelated topics and mislead the model. You can watch both methods at work in the Leiden visualizer and the Louvain visualizer, and our guide to community detection covers the wider family of methods.

Centrality: deciding what matters

A community may contain hundreds of entities, and a context window cannot hold all of them. Centrality measures decide what goes in first. Microsoft’s implementation uses node degree, the number of relationships an entity has, to prioritise entities and edges when it writes reports and builds query context. HippoRAG and several later systems use Personalized PageRank, which ranks nodes by how often a random walk that keeps restarting at the question’s entities visits them. Betweenness centrality highlights brokers, entities that sit on many shortest paths between groups and are often single points of failure. Our article on graph centrality measures compares these measures in depth.

Traversal and shortest paths

Local search starts from the entities named in a question and expands outward. Breadth-first search collects the k-hop neighbourhood of an entity, shortest-path algorithms connect two named entities, and constrained path queries follow only certain edge types, such as SUPPLIES or PART_OF. Because the LLM’s context is limited, these traversals are usually capped at two or three hops and pruned by edge weight or centrality.

Subgraph selection, embeddings and link prediction

Some systems treat retrieval itself as an optimisation problem. G-Retriever (He et al., 2024), for example, selects the subgraph to show the model by solving a prize-collecting Steiner tree problem: relevant nodes earn prizes, edges cost something, and the best subgraph connects the most valuable nodes as cheaply as possible. Other systems learn node embeddings with node2vec or graph neural networks, so that structurally similar entities are retrieved together, and use link prediction to suggest relationships the extractor missed. These are optional refinements, but they show how naturally GraphRAG plugs into the wider toolbox of graph machine learning.

Watch Leiden Find the Communities

Every GraphRAG community report starts with a partition like this one. Run the Leiden algorithm on a graph you draw yourself and watch modularity rise move by move.

Run the Leiden Algorithm

6. Answering Questions: Local, Global and DRIFT Search

Once the index exists, a GraphRAG system must decide how to use it for each question. Microsoft’s implementation offers three graph-based query modes, and other frameworks have similar ones under different names.

Local search: questions about specific entities

Local search handles questions that name or imply specific things, such as “What does Brisa Electronics supply, and to whom?” The system embeds the question and finds the most similar entity descriptions. It then builds a context from the graph around those entities: their descriptions, their relationships and neighbouring entities, the reports of the communities they belong to, and the original text units that mention them. Each source gets a share of the token budget, items are ranked within it, and the LLM answers from the assembled context.

Global search: questions about the whole corpus

Global search answers sensemaking questions such as “What are the main themes in these reports?” It works on community reports instead of entities, in a map-reduce pattern.

  1. Map. The reports at a chosen level of the hierarchy are shuffled into batches that fit the context window. For each batch, the LLM writes a partial answer as a list of points, and gives every point a helpfulness score from 0 to 100.
  2. Reduce. Points that scored 0 are dropped, the rest are sorted by score and packed into one final context, and the LLM writes the answer from the strongest points across the whole corpus.

The level matters. Top-level reports give short, broad answers cheaply, while bottom-level reports give detailed answers at a much higher cost. Global search is where GraphRAG most clearly beats vector RAG, because no amount of chunk retrieval can summarise a corpus that the retriever never sees in full.

DRIFT search: a hybrid

DRIFT search (Dynamic Reasoning and Inference with Flexible Traversal), which Microsoft added in late 2024, combines the two. It first compares the question with community reports to produce a broad initial answer and a set of follow-up questions. It then answers those follow-ups with local search, refining the result over a few rounds. DRIFT suits questions that are specific in intent but whose relevant entities are not obvious from the wording.

ModeBest forReadsRelative cost
Basic (vector)Answers that sit in one passageText-unit embeddingsLowest
LocalQuestions about specific entitiesEntities, relationships, text units, reportsLow
DRIFTSpecific but open-ended questionsReports first, then local contextMedium
GlobalThemes across the whole corpusCommunity reports, map-reduceHigh

7. A Worked Example: Tracing a Supply-Chain Risk

Consider a small corpus of supplier notes kept by a pump manufacturer. All names are fictional. Five short documents say:

  1. D1: Corvo Alloys ships all of its output through Halden Port, where Mirel Shipping operates the container terminal.
  2. D2: Corvo Alloys makes the aluminium housing for the C7 controller board.
  3. D3: Brisa Electronics assembles the C7 controller board and the S3 pressure sensor.
  4. D4: Tarn Industrial’s P200 pump uses the C7 board and the S3 sensor.
  5. D5: Vela Water Utility and Ostra Farms buy the P200 pump from Tarn Industrial.

Now ask: “If Halden Port closes, which customers are affected?”

What vector RAG retrieves

The question shares words and meaning with D1, the only document that mentions Halden Port, so D1 ranks first. D5 is the only document that mentions customers, but it says nothing about ports, so it may or may not make the top results. Even if it does, the model receives the first and the last links of a five-link chain with the middle missing. A typical answer is that Corvo Alloys and Mirel Shipping would be affected, which is true but names the wrong kind of party. The customers never appear.

What GraphRAG builds

Extraction turns the five documents into eleven entities and eleven relationships. Entity resolution merges “C7 board” in D4 with “C7 controller board” in D2 and D3, and “S3 sensor” with “S3 pressure sensor”. Without that step, the chain would break in the middle.

Mirel Shipping       -[OPERATES_AT]->    Halden Port
Corvo Alloys         -[SHIPS_THROUGH]->  Halden Port
Corvo Alloys         -[MAKES]->          Aluminium housing
Aluminium housing    -[PART_OF]->        C7 controller board
Brisa Electronics    -[MAKES]->          C7 controller board
Brisa Electronics    -[MAKES]->          S3 pressure sensor
C7 controller board  -[PART_OF]->        P200 pump
S3 pressure sensor   -[PART_OF]->        P200 pump
Tarn Industrial      -[MAKES]->          P200 pump
Vela Water Utility   -[BUYS]->           P200 pump
Ostra Farms          -[BUYS]->           P200 pump
The example knowledge graph of eleven entities split into three communities: logistics (Halden Port, Mirel Shipping, Corvo Alloys, aluminium housing), electronics (Brisa Electronics, C7 controller board, S3 pressure sensor) and product and customers (P200 pump, Tarn Industrial, Vela Water Utility, Ostra Farms). The five-hop path from Halden Port to Vela Water Utility is highlighted.
Figure 2. The example knowledge graph, its three modularity communities, and the five-hop path that answers the multi-hop question.

Community detection then splits the graph into three groups: a logistics community (Halden Port, Mirel Shipping, Corvo Alloys, aluminium housing), an electronics community (Brisa Electronics, the C7 board, the S3 sensor) and a product and customers community (the P200 pump, Tarn Industrial, Vela Water Utility, Ostra Farms). On a graph this small we can check every possible partition, and this one has the highest modularity of all of them, Q ≈ 0.39, which is what Leiden aims for.

Answering the multi-hop question with local search

The question mentions Halden Port, so local search starts there. Following the edges outward reaches Corvo Alloys, the aluminium housing, the C7 board, the P200 pump, and finally the two buyers. The shortest path to Vela Water Utility has five hops:

Halden Port → Corvo Alloys → Aluminium housing → C7 controller board → P200 pump → Vela Water Utility

The LLM receives this path, the descriptions along it, and the source sentences D1 to D5. It can now answer correctly: Vela Water Utility and Ostra Farms are exposed, because the P200 pump they buy contains the C7 board, whose housing comes from Corvo Alloys, which ships only through Halden Port. Every step of the answer cites a document, so a person can check it.

Answering a global question with community reports

Ask instead: “What are the main supply risks in these notes?” No single document answers this. Global search reads the three community reports. The logistics report notes that one supplier depends on a single port. The electronics report notes that both components inside the P200 come from one assembler. The customer report notes that two customers rely on a single product. The reduce step combines these into an answer that names the single points of failure. The graph agrees: by betweenness centrality the P200 pump and the C7 board are the two most central nodes, because nearly every path from the supply side to the customers passes through them.

This tiny example is easy for any method if all five documents fit into one prompt. GraphRAG’s advantage appears when the corpus has thousands of documents and the five relevant sentences are scattered among them.

8. Building a GraphRAG System: Tools and Code

There are three common ways to build a GraphRAG system, and they can be combined.

Option 1: Microsoft’s open-source graphrag package

The quickest way to try the full pipeline is the reference implementation. It reads plain text files, runs extraction, community detection and report generation, and supports local, global, DRIFT and basic search from the command line or from Python.

pip install graphrag
graphrag init --root ./ragtest        # creates settings.yaml, prompts and .env
# put your .txt files in ./ragtest/input and your API key in ./ragtest/.env
graphrag index --root ./ragtest       # build the graph, communities and reports
graphrag query --root ./ragtest --method global --query "What are the main supply risks?"
graphrag query --root ./ragtest --method local --query "Who buys the P200 pump?"

Before indexing a large corpus, run graphrag prompt-tune, which adapts the extraction prompts to your domain, and index a small sample first to estimate the cost.

Option 2: A graph database

When the graph must be queried by applications, updated continuously or combined with existing business data, it usually lives in a graph database. Neo4j, Memgraph, FalkorDB, Amazon Neptune, ArangoDB, NebulaGraph and TigerGraph all support GraphRAG workloads, and most now combine vector indexes on nodes with graph queries in one system. Several offer their own GraphRAG libraries. In Cypher, the multi-hop question from the worked example becomes one query:

MATCH (port:Location {name: "Halden Port"})
      <-[:SHIPS_THROUGH]-(supplier:Organization)
      -[:MAKES]->(part:Product)
      -[:PART_OF*1..3]->(product:Product)
      <-[:BUYS]-(customer:Organization)
RETURN DISTINCT customer.name, product.name, supplier.name

A common pattern is text-to-Cypher: the LLM translates the user’s question into a query like this one, the database runs it, and the LLM phrases the result. It is precise when the schema is clean, and it combines well with vector search for the questions the schema does not cover.

Option 3: An LLM framework

LlamaIndex (with its property graph index) and LangChain (with its LLM graph transformer) can extract graphs from documents and plug graph retrieval into an existing RAG application. This route is attractive when you already have a vector-based pipeline and want to add graph retrieval step by step.

A minimal GraphRAG in Python

To understand the moving parts, it helps to build a toy version yourself. The sketch below uses NetworkX and any LLM you can call as a function. It extracts triples, builds a graph that remembers where every edge came from, detects communities, and assembles a local context ranked by Personalized PageRank.

import json
import networkx as nx

def extract_triples(text, llm):
    """Ask the LLM for (head, relation, tail) triples as JSON."""
    prompt = ("Extract entities and relationships from the text below. "
              'Return JSON: [{"head": ..., "relation": ..., "tail": ...}]\n\n' + text)
    return json.loads(llm(prompt))

def build_graph(chunks, llm):
    G = nx.MultiDiGraph()
    for chunk_id, text in chunks.items():
        for t in extract_triples(text, llm):
            # keep the source so every answer can cite its evidence
            G.add_edge(t["head"], t["tail"], relation=t["relation"], source=chunk_id)
    return G

def communities(G):
    # GraphRAG uses hierarchical Leiden; NetworkX ships Louvain, its close cousin
    return nx.community.louvain_communities(nx.Graph(G), seed=42)

def local_context(G, entity, hops=2, top=10):
    U = nx.Graph(G)
    near = nx.single_source_shortest_path_length(U, entity, cutoff=hops)
    rank = nx.pagerank(U, personalization={entity: 1.0})
    keep = sorted(near, key=rank.get, reverse=True)[:top]
    return [f"{u} {d['relation']} {v} (source: {d['source']})"
            for u, v, d in G.subgraph(keep).edges(data=True)]

On the worked example, nx.shortest_path(nx.Graph(G), "Halden Port", "Vela Water Utility") returns the five-hop chain shown above, and local_context(G, "Halden Port", hops=5, top=20) hands the LLM every relationship it needs, each tagged with its source document. A production system adds entity resolution, community reports, token budgets and a proper store, but the skeleton is the same.

9. Beyond the Original: LightRAG, HippoRAG and Friends

Microsoft’s pipeline started a wave of research, and several variants are now widely used.

The survey by Peng et al. (2024) organises this fast-moving field into graph-based indexing, graph-guided retrieval and graph-enhanced generation, and it is a good map for further reading.

10. Costs, Pitfalls and Evaluation

GraphRAG is powerful, but it is not free, and several failure modes are easy to miss in a demo.

Evaluate before you commit. Build a question set that mirrors real usage, with single-fact questions, multi-hop questions and corpus-wide questions, and compare GraphRAG with a well-tuned vector RAG baseline on the same corpus. Measure answer correctness, faithfulness to the retrieved context and the completeness of retrieval. The original GraphRAG paper used an LLM as a judge in head-to-head comparisons on comprehensiveness, diversity and empowerment, and found large gains for global questions. Your own corpus and questions are the only benchmark that settles whether those gains apply to you.

11. GraphRAG vs Vector RAG: When to Use Which

The two approaches are not rivals so much as tools for different questions. The table summarises the trade-offs, including a third option, querying an existing knowledge graph directly.

CriterionVector RAGGraphRAGQuery an existing knowledge graph
InputUnstructured textUnstructured textA curated graph
Indexing costLow (embeddings)High (LLM extraction and reports)None if the graph exists
Single-fact questionsStrongStrongStrong within the schema
Multi-hop questionsWeakStrongStrong
Corpus-wide themesWeakStrong (global search)Weak
ExplainabilityRetrieved passagesPaths, passages and reportsThe exact query
Keeping it currentEasyHarderTransactional updates

GraphRAG is likely to pay off when:

Plain vector RAG is usually enough when questions are answered by one passage, documents change by the minute, or the budget for indexing is tight. In practice, many teams end up with a hybrid: vector search for the easy questions, graph traversal for the connected ones, and community summaries for the big-picture ones.

Either way, GraphRAG is a reminder that the foundations still matter. Breadth-first search, shortest paths, centrality and community detection, the topics of any first course in graph theory and network science, are now part of how AI systems decide what to read. If you understand those algorithms, you understand why GraphRAG works and where it will break.

Interactive visualizers: Leiden community detection, Louvain community detection, PageRank, Personalized PageRank, Betweenness centrality, Steiner tree, node2vec and DeepWalk and Link prediction (Adamic-Adar), each run step by step on a graph you can edit.

Frequently Asked Questions

What is GraphRAG in simple terms?

GraphRAG is retrieval-augmented generation that uses a knowledge graph. An LLM first reads your documents and records the entities they mention and the relationships between them. At question time the system follows those relationships and reads summaries of related groups of entities, so it can connect facts from different documents and answer questions about the collection as a whole.

What is the difference between GraphRAG and normal RAG?

Normal (vector) RAG retrieves the text chunks whose embeddings are most similar to the question. GraphRAG adds a knowledge graph built from the same text, so it can follow chains of relationships across documents and summarise whole communities of entities. Vector RAG is cheaper and simpler; GraphRAG is stronger on multi-hop and corpus-wide questions.

Which algorithm does GraphRAG use for community detection?

Microsoft’s GraphRAG uses the hierarchical Leiden algorithm. Leiden maximises modularity like Louvain but adds a refinement step that guarantees every community is internally connected, and applying it recursively gives a hierarchy of communities from broad topics down to small, specific groups.

Do I need a graph database for GraphRAG?

No. Microsoft’s reference implementation stores its graph, communities and reports in Parquet files. A graph database becomes useful when the graph is large, changes often, must be queried with Cypher or GQL, or has to sit next to existing business data and access controls.

Is GraphRAG expensive?

Indexing is the expensive part, because an LLM reads every chunk to extract entities and relationships and then writes a report for every community. Querying is cheap for local search and more expensive for global search, which calls the LLM once per batch of community reports. Smaller extraction models and lazy variants such as LazyGraphRAG reduce the cost sharply.

Further Exploration

The Graph Algorithms Behind GraphRAG

Community detection, PageRank, centrality and shortest paths decide what a GraphRAG system reads. Run each of them step by step on a graph you build yourself.

Open the Visualizer