GraphRAG: Knowledge Graphs for Retrieval
Generative & Agentic AI · Retrieval-Augmented Generation · Advanced · 28 min
See why top-k vector search fails on multi-hop and whole-dataset questions, build a knowledge graph from text with an LLM, answer with local search (walk out from the matched entities) or global search (community summaries), and run it on AWS with Neptune Analytics and Bedrock Knowledge Bases.
A detective's wall: index cards for people and companies, red string between them. To answer 'who is behind this app?' you put your finger on the app's card and follow the string, card by card, instead of searching the drawer for the one note that says it all.
The idea in everyday words
Vector RAG is a librarian who hands you the three pages that sound most like your question. That works when one page holds the answer. But if the answer is spread out (page 12 says the app was built by Orbit Labs, page 80 says Orbit Labs was founded by Priya Rao), the librarian never brings page 80, because it never mentions the app. GraphRAG first draws a map of who is connected to what, then follows the map from the things your question names.
Where plain vector RAG breaks
Plain RAG (see RAG and Advanced RAG) embeds your question, finds the top-k most similar chunks and pastes them into the prompt. It shines when one chunk contains the answer. Two kinds of questions break it.
1. Multi-hop questions. The answer needs facts from several chunks that are linked by an entity (a person, company, product, place).
| Chunk | Text |
|---|---|
| c1 | Atlas is a route planning app built by Orbit Labs. |
| c2 | Orbit Labs was founded by Priya Rao in 2019. |
| c5 | Atlas users love the offline maps. |
| c6 | The Atlas app won a design award. |
Question: "Who founded the company that built Atlas?" The top-3 similar chunks are c1, c5 and c6: they all say "Atlas". The answer is in c2, which never mentions Atlas, so it scores low and is never retrieved. Each hop needs a fact the question does not name. Raising k only adds more chunks about Atlas.
2. Global (sensemaking) questions. "What are the main themes across these 10,000 support tickets?" No single chunk is about "the main themes". Top-k returns 5 random-looking tickets and the model summarises those 5, not the whole set.
| Question type | Example | Plain vector RAG |
|---|---|---|
| Single fact | "What is the refund window?" | Great |
| Multi-hop | "Who founded the company that built Atlas?" | Misses the second hop |
| Global | "What are the main risks mentioned across all reports?" | Sees only k chunks |
| Exact codes | "Error E42" | Use hybrid search (Advanced RAG) |
# Tiny "embedding": count shared words. The founder chunk shares only one word.
q = {"founded", "company", "built", "atlas"}
chunks = {
"c1": {"atlas", "route", "planning", "app", "built", "orbit", "labs"},
"c2": {"orbit", "labs", "founded", "priya", "rao", "2019"},
"c5": {"atlas", "users", "love", "offline", "maps"},
"c6": {"atlas", "app", "won", "design", "award"},
}
for cid, words in chunks.items():
print(cid, "shares", sorted(q & words))
Key idea: similarity finds text that LOOKS like the question. Multi-hop and global questions need text that is CONNECTED to it.
Building the graph: an LLM reads every chunk
A knowledge graph stores entities (nodes: Atlas, Orbit Labs, Priya Rao) and relations (edges: built by, founded by). Each edge is one fact, a triple (subject, relation, object).
You build it at indexing time, before any question arrives:
- Chunk the documents as in normal RAG.
- Extract with an LLM: for each chunk, ask for the entities (name, type, short description) and the relations between them, as JSON.
- Resolve entities: "Orbit Labs", "Orbit" and "OrbitLabs Inc." must become ONE node, or the hops break. Normalise names, then merge by name similarity, embeddings or an LLM check.
- Keep provenance: every node and edge remembers which chunk ids it came from, so answers can cite sources.
- Store nodes, edges and chunk embeddings in a graph database (often with a vector index on the same nodes).
{
"chunk_id": "c2",
"entities": [
{"name": "Orbit Labs", "type": "Company", "description": "Maker of the Atlas app"},
{"name": "Priya Rao", "type": "Person", "description": "Founder of Orbit Labs"}
],
"relations": [
{"source": "Orbit Labs", "relation": "founded by", "target": "Priya Rao", "chunk": "c2"}
]
}
Two styles you will hear about:
| Style | Nodes | Good for |
|---|---|---|
| Entity graph | entities and typed relations (Person founded Company) | multi-hop facts, precise questions |
| Lexical graph | documents, chunks and the entities each chunk mentions | linking chunks that talk about the same things, with less schema work |
Tips that matter in practice:
- Give the extractor a small schema (allowed entity types and relations). Free-form extraction invents a different relation name for every sentence.
- Extraction is the expensive part: one or more LLM calls per chunk. Run it in batches, cache it, and re-extract only changed chunks.
- Extraction makes mistakes (wrong relation, missed entity). Spot-check a sample, like you would label data.
// Writing one fact into a graph with openCypher (Amazon Neptune supports openCypher)
MERGE (a:Entity {name: 'Orbit Labs'}) SET a.type = 'Company'
MERGE (b:Entity {name: 'Priya Rao'}) SET b.type = 'Person'
MERGE (a)-[r:FOUNDED_BY]->(b)
SET r.chunks = ['c2']
Key idea: the graph turns hidden links between chunks into explicit edges you can walk.
Local search: start at the question's entities and walk
Local search answers questions about specific things.
- Link the question to entities. Find the entities the question names: string match on entity names, an NER model, or vector search over entity descriptions. Here: Atlas. These are the seeds.
- Expand k hops. Breadth-first: hop 1 collects every fact touching a seed and the neighbours it reaches; hop 2 does the same from those neighbours. Walk edges in both directions: "Orbit Labs founded by Priya Rao" must be found from Priya Rao too.
- Collect context. The facts, the entity descriptions and the source chunks of those facts (provenance).
- Rank and trim. Not every neighbour is relevant (the design award does not answer "who founded"). Score facts or chunks against the question, keep the best that fit the token budget.
- Generate with citations.
With seeds ["Atlas"] and 2 hops:
| Hop | From | New facts |
|---|---|---|
| 1 | Atlas | Atlas built by Orbit Labs · Atlas has feature Offline Maps · Atlas won Design Award |
| 2 | Design Award, Offline Maps, Orbit Labs | Orbit Labs founded by Priya Rao |
The founder appears at hop 2, exactly where vector search gave up. This BFS is this lesson's challenge.
Watch the fan-out. If each entity has about d neighbours, k hops can reach about d^k entities. Popular "hub" entities (a country, "AWS", "customer") connect to everything.
for degree in [5, 30]:
for hops in [1, 2, 3]:
print("degree", degree, "| hops", hops, "| up to", degree ** hops, "entities")
Controls: keep k small (1 to 2 is common), cap neighbours per node, skip or down-weight hubs, filter by relation type, and rank before you put anything in the prompt.
Key idea: local search = entity linking + a bounded BFS + ranking, with sources attached to every fact.
Global search: communities and their summaries
For "What are the main themes?" there is no entity to start from. Microsoft's GraphRAG approach (Edge et al., 2024, From Local to Global) prepares for these questions at indexing time:
- Community detection. Run an algorithm that groups densely connected entities. GraphRAG uses hierarchical Leiden: big communities split into smaller ones, giving levels from "whole dataset" down to "small topic".
- Community reports. An LLM writes a summary for each community: its key entities, relations and claims.
- Map. At question time, each community report (or batch of reports) is sent to the LLM with the question: "what does this part say about it, and how useful is it, 0 to 100?"
- Reduce. Drop the useless partial answers, sort by score, pack the best into one prompt and write the final answer.
# Map step output: (helpfulness 0-100, partial answer) per community report.
partials = [
(85, "Product: Atlas is a route app with offline maps and an award."),
(0, "Weather data: nothing relevant."),
(70, "Company: Orbit Labs, founded by Priya Rao, builds Atlas."),
(40, "People: Priya Rao previously worked at Nimbus in Lisbon."),
]
budget = 2 # how many partial answers fit in the final prompt
useful = sorted([p for p in partials if p[0] > 0], reverse=True)[:budget]
for score, text in useful:
print(score, text)
| Local search | Global search | |
|---|---|---|
| Question | about named things | about the whole corpus |
| Starts from | seed entities | community reports |
| Query cost | low: one graph walk + one LLM call | high: many map calls + a reduce call |
| Index cost | extraction | extraction + community detection + one summary per community |
Microsoft GraphRAG also offers DRIFT search, which mixes the two: it starts from community-level context and then follows up with local searches.
Key idea: global questions are answered from summaries prepared in advance, combined with map-reduce, not from k raw chunks.
Hybrid retrieval, cost and freshness
In practice you rarely choose graph OR vectors. Hybrid graph + vector is the common shape:
- Vector search finds the best chunks (fast, handles fuzzy wording).
- Look up the entities those chunks mention.
- Walk the graph from those entities to pull in connected chunks the vector search missed.
- Rerank everything and send the best to the LLM.
This is how Amazon Bedrock Knowledge Bases GraphRAG works (next section): an initial vector search, then graph traversal to related chunks.
Is GraphRAG worth it? It costs more to build and keep fresh.
| Concern | What happens | Mitigation |
|---|---|---|
| Index cost | LLM extraction over every chunk, plus community summaries | smaller extraction model, a schema, only index what needs multi-hop |
| Freshness | new documents add entities and edges; communities and their summaries go stale | incremental extraction for changed chunks; rebuild communities on a schedule |
| Extraction errors | a wrong edge gives a confident wrong answer | provenance on every edge, show citations, sample and review |
| Entity resolution | "Orbit" and "Orbit Labs" as two nodes break hops | normalisation, merge step, aliases |
| Latency | graph walk + more context | small k, caps per node, cache popular subgraphs |
Use GraphRAG when questions really are multi-hop (supply chains, org charts, research literature, investigations, compliance across contracts) or global (themes across a corpus). For FAQ-style single-fact questions, plain RAG with hybrid search and reranking is cheaper and just as good. Measure both on the same test set before deciding.
Key idea: add a graph when your questions follow links; keep vectors for the fuzzy first step.
GraphRAG on AWS
Amazon Neptune is AWS's managed graph database family:
- Neptune Database: a transactional graph database (openCypher, Gremlin, SPARQL), good as the system of record for a graph that is updated all the time.
- Neptune Analytics: an in-memory analytics graph engine queried with openCypher. It can store vector embeddings on nodes with a vector index (HNSW) for similarity search, and runs built-in graph algorithms as openCypher procedures (
CALL neptune.algo...), including breadth-first search, PageRank and community detection such as Louvain and Leiden. So entity lookup, graph walk and vector search can live in one store.
Amazon Bedrock Knowledge Bases GraphRAG is the managed path. You create a knowledge base with Neptune Analytics as the store. During ingestion, a foundation model you choose (the graph construction model) extracts entities and relationships and builds the graph with the chunk embeddings. At query time it does an initial vector search, then traverses the graph to related chunks, and returns them through the normal Retrieve / RetrieveAndGenerate APIs. Limits to know (check the docs, they change): only Amazon S3 as the data source, no options to customise how the graph is built, and no autoscaling for the Neptune Analytics graph. Deleting the knowledge base does not delete the graph, so delete the graph too or it keeps costing money.
# boto3: querying a GraphRAG knowledge base is the usual Retrieve call
import boto3
rt = boto3.client("bedrock-agent-runtime")
resp = rt.retrieve(
knowledgeBaseId="KB12345678",
retrievalQuery={"text": "Who founded the company that built Atlas?"},
)
for r in resp["retrievalResults"]:
print(r["content"]["text"][:80])
// Neptune Analytics, openCypher: facts up to 2 hops from 'Atlas' (both directions)
MATCH (a:Entity {name: 'Atlas'})-[r1]-(b:Entity)
OPTIONAL MATCH (b)-[r2]-(c:Entity)
RETURN a.name, type(r1), b.name, type(r2), c.name
LIMIT 100
Build-your-own on AWS: Lambda or Step Functions run extraction with a Bedrock model, Neptune stores the graph, OpenSearch or Neptune Analytics holds vectors, and AWS's open-source graphrag-toolkit (awslabs on GitHub) builds a lexical graph for you. Check the Neptune and Bedrock pricing pages before sizing.
Open source elsewhere: Microsoft GraphRAG, Neo4j (graph database with vector indexes and a GraphRAG package), LlamaIndex property graph index, and LightRAG.
Go deeper (engineer level)
Evaluate multi-hop separately. Build test questions that need 2 or 3 hops (benchmarks like HotpotQA and MuSiQue are built this way) and track, per question, whether every needed fact was retrieved (fact recall) before judging the answer. A graph that helps 2-hop questions can hurt single-fact ones by adding noise, so report both.
Entity linking is the weak spot. If the question says "the Orbit team" and the node is "Orbit Labs", local search starts nowhere. Link with fuzzy names plus embeddings of entity descriptions, and fall back to vector search over chunks when no entity matches.
Ranking inside the walk. Instead of plain BFS, score each frontier node or edge against the question (embedding similarity of the relation and description), keep the best few per hop (a beam), or use personalised PageRank from the seeds. This keeps hub explosions under control.
Community levels. Reports exist at several levels of the Leiden hierarchy. Higher levels are cheaper to map over (fewer reports) but vaguer; lower levels are detailed but many. Pick the level per question type and measure.
Freshness strategy. Separate the fast path (new chunks embedded and extracted within minutes, edges added incrementally) from the slow path (community detection and report regeneration nightly or weekly). Version the graph so an answer can say which snapshot it used.
Security. Apply document-level permissions to graph facts too: a fact extracted from a restricted chunk must not leak through a hop. Carry the source chunk's access tags on every edge and filter during the walk.
Step by step
- Extract the graph:
At indexing time an LLM reads the six chunks and returns one fact each: (Atlas, built by, Orbit Labs), (Orbit Labs, founded by, Priya Rao), (Priya Rao, worked at, Nimbus), (Nimbus, based in, Lisbon), (Atlas, has feature, Offline Maps), (Atlas, won, Design Award). Seven entities, six edges, each edge remembers its chunk.
- Link the question:
Question: 'Who founded the company that built Atlas?'. The only entity it names is Atlas, so seeds = [Atlas]. We will walk k = 2 hops.
- Hop 1:
From Atlas, walk every edge in both directions: built by Orbit Labs (c1), has feature Offline Maps (c5), won Design Award (c6). Three facts. New frontier, sorted: [Design Award, Offline Maps, Orbit Labs].
- Hop 2:
Design Award and Offline Maps only lead back to Atlas (facts we already have). Orbit Labs gives one new fact: founded by Priya Rao (c2). Priya Rao is discovered at distance 2. Stop: k = 2.
- Compare with vector top-3:
Ranking the chunks by similarity to the question gives c1, c6, c5: all of them mention Atlas. c2, the only chunk with the founder, ranks 4th because it never says 'Atlas'.
- Answer:
The prompt gets the 4 facts plus their source chunks c1, c5, c6, c2. The model answers 'Priya Rao founded Orbit Labs, which built Atlas' and cites c1 and c2. A ranking step would also drop the award and offline maps facts, which do not help.
Code example
# Vector top-k vs a 2-hop graph walk on the same six chunks.
import math
from collections import Counter
CHUNKS = {
"c1": "Atlas is a route planning app built by Orbit Labs.",
"c2": "Orbit Labs was founded by Priya Rao in 2019.",
"c3": "Priya Rao previously worked at Nimbus.",
"c4": "Nimbus is headquartered in Lisbon.",
"c5": "Atlas users love the offline maps.",
"c6": "The Atlas app won a design award.",
}
# What an LLM extraction step returned for each chunk: (subject, relation, object)
TRIPLES = {
"c1": ("Atlas", "built by", "Orbit Labs"),
"c2": ("Orbit Labs", "founded by", "Priya Rao"),
"c3": ("Priya Rao", "worked at", "Nimbus"),
"c4": ("Nimbus", "based in", "Lisbon"),
"c5": ("Atlas", "has feature", "Offline Maps"),
"c6": ("Atlas", "won", "Design Award"),
}
STOP = {"the", "a", "is", "by", "in", "was", "at", "who", "that", "of"}
def words(text):
clean = "".join(ch.lower() if ch.isalnum() else " " for ch in text)
return Counter(w for w in clean.split() if w not in STOP)
def cosine(a, b):
dot = sum(a[w] * b[w] for w in a)
na = math.sqrt(sum(v * v for v in a.values()))
nb = math.sqrt(sum(v * v for v in b.values()))
return dot / (na * nb) if na and nb else 0.0
question = "Who founded the company that built Atlas?"
q = words(question)
ranked = sorted(CHUNKS, key=lambda c: (-cosine(q, words(CHUNKS[c])), c))
print("vector top-3:", ranked[:3])
# Graph: adjacency in both directions, remembering the source chunk of each edge.
adj = {}
for cid, (s, r, o) in TRIPLES.items():
adj.setdefault(s, []).append((o, cid))
adj.setdefault(o, []).append((s, cid))
seeds = [e for e in adj if e.lower() in question.lower()]
seen, frontier, found = set(seeds), sorted(seeds), []
for hop in range(2):
nxt = []
for node in frontier:
for nb, cid in adj[node]:
if cid not in found:
found.append(cid)
if nb not in seen:
seen.add(nb)
nxt.append(nb)
frontier = sorted(nxt)
print("seed entities:", seeds)
print("graph, 2 hops:", found)
for cid in found:
print(" ", cid, "|", " ".join(TRIPLES[cid]))
print("founder chunk c2 in vector top-3?", "c2" in ranked[:3], "| in graph result?", "c2" in found)Complexity
- Time: O(V + E) for multi_hop_facts: each reached entity is expanded once and each of its edges looked at once (plus sorting each frontier)
- Space: O(V + E) for the adjacency list, the visited set and the collected facts
Interview tips
Explain with a concrete example why top-k vector search fails on a multi-hop question, and how a knowledge graph fixes it.
Walk through building a knowledge graph from documents: chunking, LLM extraction with a schema, entity resolution, provenance, storage. Where does it go wrong?
Local vs global search in GraphRAG: what each is for, how global search uses community detection and map-reduce, and what each costs.
Design GraphRAG on AWS: Bedrock Knowledge Bases with Neptune Analytics versus building your own with Neptune and Bedrock models. What are the managed option's limits?
How would you prove GraphRAG is worth the extra indexing cost? Talk about a multi-hop test set, fact recall, latency and refresh cost.
Challenge: Collect facts within k hops
Write multi_hop_facts(triples, seeds, k), the retrieval step of GraphRAG local search.
triples: a list of[subject, relation, object]strings. Each one is a fact:"subject relation object"(joined with single spaces).seeds: the entities the question names.k: the number of hops to walk.
Rules:
- A fact connects its two entities in both directions.
- Walk breadth-first. Hop 1 expands the seeds, hop 2 expands the entities first reached in hop 1, and so on, for
khops. Expanding an entity collects every fact that touches it. - Within one hop, expand entities in alphabetical order. For one entity, take its facts in the order they appear in
triples. - Each fact appears once, at the first time it is collected. Each entity is expanded at most once.
- Seeds that are not in any triple are ignored.
k = 0returns[]. A negativekraisesValueError(JavaScript: throw anError).
triples = [["Atlas", "built by", "Orbit Labs"], ["Orbit Labs", "founded by", "Priya Rao"],
["Priya Rao", "worked at", "Nimbus"], ["Nimbus", "based in", "Lisbon"],
["Atlas", "has feature", "Offline Maps"], ["Atlas", "won", "Design Award"]]
multi_hop_facts(triples, ["Atlas"], 2)
# → ["Atlas built by Orbit Labs", "Atlas has feature Offline Maps",
# "Atlas won Design Award", "Orbit Labs founded by Priya Rao"]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Microsoft GraphRAG documentation (indexing, local, global and DRIFT search) (Medium)
- AWS docs: Build a knowledge base with graphs from Amazon Neptune Analytics (Medium)
- From Local to Global: A Graph RAG Approach to Query-Focused Summarization (paper) (Hard)
- All Nodes Distance K in Binary Tree (Medium)
More in Retrieval-Augmented Generation
- RAG: Chat With Your Own Documents
- Vector Databases & Similarity Search
- Advanced RAG: Chunking, Hybrid Search & Reranking
- Bedrock Knowledge Bases: Managed RAG
Previous: Bedrock Knowledge Bases: Managed RAG · Next: What Is Agentic AI?