Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Retrieval (RAG)AI guideAdvanced#rag#graphrag#knowledge-graph#retrieval
Frame · ai-engineering / rag / 10-graphrag-and-knowledge-graphs.mdGuide 022 / 103

GraphRAG and knowledge graphs

Vector RAG answers "where is the passage that says X" very well. It struggles with two other kinds of question: global questions about a whole corpus ("what are the main themes in these 2,000 customer interviews?") and multi-hop questions that need facts from several documents connected by entities ("which suppliers of our top three products are based in regions affected by the new tariff?"). GraphRAG approaches build a graph of entities and relationships from the corpus and retrieve over that structure. This doc explains how they work, what Microsoft's GraphRAG and LazyGraphRAG do differently, and when the extra machinery pays off.

Why it matters

Top-k chunk retrieval is a local operation. It returns the handful of passages most similar to the query. If the answer is spread across hundreds of passages, or if it depends on a chain of relationships none of which resembles the question text, the right evidence never reaches the model. Microsoft Research's framing is direct: vector RAG excels at local queries where the answer resembles the query, typical of "who, what, when, where" questions, while GraphRAG's advantage is answering global queries about the entire dataset.

Knowledge graphs also give you something chunks do not: explicit, inspectable structure. You can see that entity A is related to entity B through document C, which is valuable for explanation and audit in domains like compliance, research and investigations.

How it works

Microsoft's GraphRAG (paper: "From Local to Global", 2024) indexes a corpus in stages:

  1. Chunk the source text into text units.
  2. Extract entities, relationships and claims from each unit with an LLM.
  3. Build a graph with entities as nodes and relationships as edges, merging duplicates.
  4. Detect communities with hierarchical clustering (the Leiden algorithm), giving nested groups of closely related entities.
  5. Summarize each community with an LLM, at each level of the hierarchy.

Querying then has several modes:

  • Global search maps the question over community summaries (each produces a partial answer) and reduces them into a final answer. Good for themes and corpus-wide questions.
  • Local search finds entities related to the question and gathers their neighbours, relationships, claims and source text units. Good for questions about specific entities.
  • DRIFT search extends local search with community information for broader context.
Rendering diagram…

The catch is indexing cost: an LLM reads every chunk for extraction and then writes every community summary. On a large corpus that is a lot of tokens, and it must be redone (at least partly) as data changes.

LazyGraphRAG is Microsoft Research's response. It defers LLM work to query time: indexing uses cheap NLP to build the concept graph, and at query time it combines best-first and breadth-first search with iterative deepening, controlled by a single relevance test budget. Microsoft reported that it matched GraphRAG global search answer quality at a small fraction of the query cost and outperformed competing methods on local queries at a cost comparable to vector RAG. Its near-free indexing makes it suited to exploratory or one-off analysis.

Outside Microsoft's project, "GraphRAG" also describes simpler patterns that work well: store entities and relationships in a graph database (Neo4j, or tables in Postgres), retrieve chunks with vector search, then expand along the graph to pull in connected facts.

Reference architecture

A pragmatic hybrid that many teams run: vector retrieval for local questions, graph expansion for multi-hop, community summaries for global.

Rendering diagram…

Code

Microsoft's GraphRAG ships as a Python package with a CLI. Initializing, indexing and querying a project looks like this:

pip install graphrag
graphrag init --root ./ragtest          # writes settings.yaml and .env
# put .txt files in ./ragtest/input, set your API key in ./ragtest/.env
graphrag index --root ./ragtest
graphrag query --root ./ragtest --method global --query "What are the main themes?"
graphrag query --root ./ragtest --method local --query "Who are the key partners of Acme?"

And a lightweight version of graph expansion with networkx, given triples you have already extracted (with an LLM or a rules-based extractor) and linked to chunk ids:

import networkx as nx

triples = [  # (subject, relation, object, chunk_id)
    ("Acme Widget", "supplied_by", "Borealis Metals", "c17"),
    ("Borealis Metals", "located_in", "Region North", "c42"),
    ("Region North", "affected_by", "2026 tariff", "c88"),
]

g = nx.MultiDiGraph()
for s, rel, o, chunk in triples:
    g.add_edge(s, o, relation=rel, chunk=chunk)

def expand(seeds: list[str], hops: int = 2) -> set[str]:
    """Return chunk ids reachable within `hops` of the seed entities."""
    undirected = g.to_undirected(as_view=True)
    chunks: set[str] = set()
    for seed in seeds:
        if seed not in g:
            continue
        reach = nx.single_source_shortest_path_length(undirected, seed, cutoff=hops)
        sub = g.subgraph(reach.keys())
        chunks |= {d["chunk"] for _, _, d in sub.edges(data=True)}
    return chunks

print(expand(["Acme Widget"], hops=3))  # {'c17', 'c42', 'c88'}

Those three chunk ids, none of which mentions the others' subject, together answer the multi-hop tariff question. Vector search on the question alone would likely only find one of them.

Trade-offs and pitfalls

  • Indexing cost is real. Full GraphRAG runs LLM extraction over the entire corpus and summarizes every community. Prototype on a slice and measure tokens before committing.
  • Entity resolution is the hard part. "IBM", "International Business Machines" and "IBM Corp." must merge into one node, or the graph fragments. Budget effort here.
  • Extraction errors compound. A wrong relationship is now a structural fact that expansion will follow. Keep source chunk ids on every edge so answers stay traceable.
  • Freshness. Incremental updates to graphs and community summaries are more complex than appending vectors.
  • Not every corpus needs it. If your questions are mostly local lookups, a good hybrid plus reranking pipeline will beat GraphRAG on cost and latency. Classify your real query traffic first.
  • Global answers are hard to evaluate. There is no single gold chunk for "main themes". Use rubric-based or pairwise LLM judging, as Microsoft's own evaluations did, and review samples by hand.

Checklist

  • Classify your real queries into local, multi-hop and global before choosing an approach.
  • Start with vector RAG plus graph expansion for multi-hop needs; adopt community summaries only for genuinely global questions.
  • Try LazyGraphRAG-style deferred approaches when indexing cost or freshness is a concern.
  • Invest in entity resolution and keep chunk provenance on every edge.
  • Measure indexing token cost on a sample before scaling.
  • Evaluate global answers with rubrics or pairwise comparison, plus human review.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.