# GraphRAG: entities, communities and global questions

Questions such as 'what were the main complaint themes?' have no single matching chunk. GraphRAG builds a graph of entities and communities so it can answer them.

<div data-sim="ragx" data-v="graphrag"><p>Interactive simulation. It needs JavaScript; the text below explains what it shows.</p></div>

## What you are looking at

Step 1 lists the extracted entities, step 2 shows the communities and their summaries, step 3 runs either a global map–reduce over summaries or a local walk from the question's entities. The graph on the right highlights the path. All RAG simulations share one knowledge base of 18 chunks from 11 documents of a fictional outdoor-gear shop, and three questions: one phrased differently from the documents, one that needs two documents, and one about the whole corpus.

## Things to try

- Run the complaints question: global search over community summaries.
- Run the fabric question: a local walk from Ridge 2 to Aurora fabric to Lumen Textiles.
- Compare with agentic RAG, which reaches the same facts with search hops.

## How it works in real systems

Microsoft's GraphRAG uses an LLM to extract entities and relations, the Leiden algorithm to find communities and LLM-written community reports. Indexing is expensive, so it suits stable corpora with analytical questions.

## Code lab

The same idea in real code, step by step. Copy each block into a notebook or a file and run it in order.

<div class="cl-start"></div>

### Step 1 · Extract entities and relations

An LLM reads every chunk and returns entities and relations as JSON. Build a graph from them.

```python
# pip install networkx openai
import json, networkx as nx

from openai import OpenAI
client = OpenAI()                                              # reads OPENAI_API_KEY
def ask(prompt, model="gpt-4o-mini"):
    r = client.chat.completions.create(model=model, messages=[{"role": "user", "content": prompt}], temperature=0)
    return r.choices[0].message.content

G = nx.Graph()
for i, c in enumerate(chunks_text := [
    "The Ridge 2 tent uses Aurora ripstop fabric.", "Aurora ripstop fabric is woven by Lumen Textiles in Porto.",
    "Q3 complaints were mostly about late deliveries.", "Summit 45 zips jammed in cold weather, a Q3 complaint."]):
    data = json.loads(ask('Extract entities and relations from the text as JSON {"entities": [..], "relations": [[a, relation, b], ..]}. Text: ' + c))
    for e in data["entities"]: G.add_node(e)
    for a, r, b in data["relations"]: G.add_edge(a, b, relation=r, chunk=i)
print(G.edges(data=True))
```

### Step 2 · Communities and summaries

```python
from networkx.algorithms.community import louvain_communities    # GraphRAG uses Leiden; Louvain is a close cousin
comms = louvain_communities(G, seed=0)
summaries = [ask("Summarise what these facts have in common:\n" + "\n".join(f"{a} {d['relation']} {b}" for a, b, d in G.subgraph(c).edges(data=True))) for c in comms]
```

### Step 3 · Local and global search

Local search walks out from the entities named in the question; global search maps the question over every community summary and reduces the partial answers.

```python
def local(q, hops=2):
    start = [n for n in G if n.lower() in q.lower()]
    near = set(start)
    for _ in range(hops): near |= {m for n in near for m in G.neighbors(n)}
    facts = [f"{a} {d['relation']} {b}" for a, b, d in G.subgraph(near).edges(data=True)]
    return ask(f"Answer from these facts:\n{chr(10).join(facts)}\nQ: {q}")
def global_search(q):
    partial = [ask(f"Using this summary, answer if you can, else say 'none': {q}\n{s}") for s in summaries]
    return ask(f"Combine these partial answers into one: {partial}\nQ: {q}")
```

Microsoft's implementation does all of this from the command line: `graphrag init --root ./kb`, `graphrag index --root ./kb`, `graphrag query --root ./kb --method global --query "..."`.

<div class="cl-end"></div>

## More simulations

[← Agentic RAG](/ai-simulations/rag-agentic) · [All AI Simulations](/ai-simulations) · [Chunking →](/ai-simulations/chunking-strategies)
