Search Tutorials
--Ads--Project 5: GraphRAG over a Document Collection
Build a knowledge graph with community summaries and answer global questions.
This project turns the mini GraphRAG from GraphRAG: Knowledge Graphs for Retrieval into a complete tool for a real document collection, such as a year of incident reports, project updates or meeting notes. It extracts a knowledge graph in parallel, merges duplicate entities, detects and summarises communities, saves everything to disk, and answers both global questions ("What were the recurring causes of outages this year?") and local ones ("Who worked on the payments migration?").
Pipeline
- Chunk all documents in a folder.
- Extract entities and relationships from each chunk, in parallel.
- Resolve entities: merge names that refer to the same thing ("Payments Team" and "Payments team (Pune)").
- Build the graph and detect communities.
- Summarise each community.
- Save the graph, chunks and summaries as JSON.
- Query in global or local mode.
pip install anthropic networkx sentence-transformers numpy pydantic
"""GraphRAG over a folder of text files.
python graphrag_project.py index reports/
python graphrag_project.py query "What were the main causes of incidents?" --mode global
"""
import argparse
import json
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import networkx as nx
import numpy as np
from sentence_transformers import SentenceTransformer
from mini_graphrag import extract, global_search # from the GraphRAG lesson
from rag_helpers import ask
OUT = Path("graphrag_out")
embedder = SentenceTransformer("BAAI/bge-small-en-v1.5")
def chunk_folder(folder: str, size: int = 2500) -> dict[str, str]:
chunks = {}
for path in sorted(Path(folder).glob("*.txt")):
text = path.read_text(encoding="utf-8")
for i in range(0, len(text), size):
chunks[f"{path.name}#{i // size}"] = text[i:i + size]
return chunks
def resolve_entities(names: list[str], threshold: float = 0.92) -> dict[str, str]:
"""Map each name to a canonical name by merging very similar names."""
names = sorted(set(names), key=len) # shorter names become canonical
vectors = embedder.encode(names, normalize_embeddings=True)
canonical: dict[str, str] = {}
for i, name in enumerate(names):
if name in canonical:
continue
canonical[name] = name
sims = vectors[i + 1:] @ vectors[i]
for j in np.where(sims >= threshold)[0]:
canonical.setdefault(names[i + 1 + j], name)
return canonical
def index(folder: str) -> None:
OUT.mkdir(exist_ok=True)
chunks = chunk_folder(folder)
print(f"Extracting from {len(chunks)} chunks...")
with ThreadPoolExecutor(max_workers=4) as pool: # keep concurrency modest for rate limits
extracted = dict(zip(chunks, pool.map(extract, chunks.values())))
raw_names = [n for rels in extracted.values() for r in rels for n in (r.source.strip(), r.target.strip())]
canon = resolve_entities(raw_names)
G = nx.Graph()
for chunk_id, relations in extracted.items():
for r in relations:
s, t = canon[r.source.strip()], canon[r.target.strip()]
if s == t:
continue
G.add_node(s, type=r.source_type)
G.add_node(t, type=r.target_type)
data = G.get_edge_data(s, t, default={"relations": [], "chunks": []})
G.add_edge(s, t, relations=sorted(set(data["relations"]) | {r.relation}),
chunks=sorted(set(data["chunks"]) | {chunk_id}))
print(f"Graph: {G.number_of_nodes()} entities, {G.number_of_edges()} relationships")
summaries = []
for cid, members in enumerate(nx.community.louvain_communities(G, seed=42)):
if len(members) < 3:
continue
sub = G.subgraph(members)
facts = [f"{a} -[{', '.join(d['relations'])}]- {b}" for a, b, d in sub.edges(data=True)][:150]
summaries.append({"id": cid, "entities": sorted(members),
"summary": ask("Write a titled report (under 200 words) on this group of "
"related entities: who or what they are, how they connect, "
"and notable events.\n" + "\n".join(facts), max_tokens=700)})
print(f"Summarised {len(summaries)} communities")
(OUT / "graph.json").write_text(json.dumps(nx.node_link_data(G)), encoding="utf-8")
(OUT / "chunks.json").write_text(json.dumps(chunks), encoding="utf-8")
(OUT / "communities.json").write_text(json.dumps(summaries, indent=1), encoding="utf-8")
def local_query(question: str, G: nx.Graph, chunks: dict[str, str]) -> str:
names = list(G.nodes)
sims = embedder.encode(names, normalize_embeddings=True) @ embedder.encode(question, normalize_embeddings=True)
seeds = [names[i] for i in np.argsort(-sims)[:3]] # entities most similar to the question
facts, chunk_ids = [], []
for s in seeds:
for nb in G.neighbors(s):
d = G[s][nb]
facts.append(f"{s} -[{', '.join(d['relations'])}]- {nb}")
chunk_ids += [c for c in d["chunks"] if c not in chunk_ids]
context = "\n".join(facts[:60]) + "\n\n" + "\n\n".join(f"[{c}]\n{chunks[c]}" for c in chunk_ids[:6])
return ask(f"<context>\n{context}\n</context>\n\nAnswer using only the context; cite chunk ids "
f"in brackets.\n\nQuestion: {question}", effort="medium")
def query(question: str, mode: str) -> str:
G = nx.node_link_graph(json.loads((OUT / "graph.json").read_text(encoding="utf-8")))
if mode == "global":
summaries = json.loads((OUT / "communities.json").read_text(encoding="utf-8"))
return global_search(question, summaries)
return local_query(question, G, json.loads((OUT / "chunks.json").read_text(encoding="utf-8")))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("index").add_argument("folder")
q = sub.add_parser("query")
q.add_argument("question")
q.add_argument("--mode", choices=["global", "local"], default="local")
args = parser.parse_args()
if args.command == "index":
index(args.folder)
else:
print(query(args.question, args.mode))
Run it
python graphrag_project.py index reports/
python graphrag_project.py query "What were the recurring themes across this year's incident reports?" --mode global
python graphrag_project.py query "Which teams were involved in the payments migration?" --mode local
Compare with standard RAG
Build a normal hybrid RAG index over the same folder and ask both systems the same questions. Typically:
| Question type | Standard RAG | GraphRAG |
|---|---|---|
| Specific fact ("When did the March outage start?") | Excellent | Good (local mode) |
| Relationships ("Who works with the team that owns X?") | Often incomplete | Strong |
| Global themes ("What are the recurring causes?") | Sees only a few chunks | Strong (community summaries) |
| Indexing cost | Low | High: an LLM call per chunk and per community |
Many production systems therefore route questions: specific questions go to standard RAG, relationship and overview questions go to GraphRAG (Query Routing).
Extensions
- Use a graph database such as Neo4j for large graphs, with Cypher queries for exact relationship lookups.
- Use hierarchical community detection (Leiden at several resolutions) for summaries at different levels of detail.
- Improve entity resolution with an LLM pass over borderline merges.
- Update incrementally: re-extract only changed chunks, then rebuild affected communities.
- Try Microsoft's open-source
graphragpackage on the same data and compare.
Key takeaways
- A complete GraphRAG pipeline adds parallel extraction, entity resolution, persistence and two query modes.
- Entity resolution is essential: without it, the same entity splits into several weakly connected nodes.
- GraphRAG excels at relationship and global questions; route specific lookups to standard RAG.