Chapter 26 of 40 · ~16 min read & lab+65 XP
Chapter 26 · Generative AI

GraphRAG & Knowledge Graphs for LLMs: Multi-Hop Retrieval Beyond Vector Search

Why vector search fails on 'global themes' and 3-hop entity connections, how Knowledge Graphs + community summaries work, and Hybrid Vector + GraphRAG architectures

What Is It?

GraphRAG extracts structured Entities and Relationships (Subject, Predicate, Object) from text into a Knowledge Graph—plus hierarchical community summaries—enabling multi-hop traversal and corpus-wide reasoning.

Why Is It Required?

Standard vector RAG only finds local top-5 chunks similar to one query; it fails miserably on global questions ('What are the top 5 risk themes across all 10,000 filings?') or multi-hop links (Company A → Supplier B → Sanctioned Owner C).

Everyday Analogy: Vector RAG is like flipping to 5 isolated index cards; GraphRAG is a detective's corkboard with red yarn connecting every suspect, company, and transaction across the entire case.
Why ML Engineers & Data Scientists Actually Need This

Financial compliance, biomedical discovery, and enterprise root-cause analysis rely on multi-hop entity relationships that flat chunk vectors cannot connect.

ML / AI Engineer

Combining Neo4j/graph traversal with vector retrieval lets you answer 3-hop queries in milliseconds without stuffing 100 chunks into the prompt.

Data Scientist

Hierarchical community summaries unlock map-reduce answers to corpus-wide 'what are the main trends?' queries.

Interview & Debug Edge

Increasingly common senior AI question: 'When does standard Hybrid Vector RAG fail, and how does GraphRAG solve it—plus what is the cost tradeoff?'

Step 0 · Test Your Gut Before Any Math!

Which query MOST clearly requires GraphRAG over standard Vector RAG?

What You Will Master in This Chapter
  • Identify the two exact query types where Vector RAG fails and GraphRAG excels: Multi-Hop Entity Traversal and Global Corpus Sensemaking.
  • Trace the GraphRAG indexing pipeline: Entity/Relation Extraction → Graph Construction → Community Detection (Leiden) → Hierarchical Summaries.
  • Compare GraphRAG indexing cost vs. Vector RAG and know when Hybrid Vector + Graph is worth the complexity.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 1
(s,r,o)∈G(s, r, o) \in \mathcal{G}Say aloud:“Knowledge Graph triple”
Plain-English Meaning
Directed edge connecting Subject entity s to Object entity o via Relation r.
Everyday Example
(Acme_Corp, SUPPLIED_BY, ChipCo), (ChipCo, OWNED_BY, Holding_X).
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Flat chunk retrieval sees islands of text; a Knowledge Graph builds bridges between entities across documents, and community summaries give you a bird's-eye map of the whole corpus.

1. Vector RAG vs. GraphRAG Cost & Capability Tradeoff

DimensionVector / Hybrid RAGGraphRAG
Indexing CostCheap (fast embeddings)Expensive (LLM entity extraction per chunk!)
Single-Fact LookupFast & accurateOverkill
Multi-Hop Entity ChainsWeak (misses intermediate hops)Strong (exact 2–3 hop graph traversal)
Global Themes ('Across all docs...')Fails (only sees top-K chunks)Strong (hierarchical community summaries)
“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

No! GraphRAG indexing costs 10×–50× more tokens than embeddings and requires entity deduplication. Start with Hybrid RAG (BM25 + Dense + Reranker) and add a Knowledge Graph only when multi-hop entity links or global summaries are core product needs.

Interactive Visual Lab
Lab Challenge: Compare how structured multi-source retrieval fuses signals cleanly.
Interactive Animation • 4.4 Deep Lab

Dual-Branch BM25 + Dense Vector → RRF Fusion Animator

Watch exact lexical BM25 and semantic Dense search run in parallel and merge via rank-only Reciprocal Rank Fusion.

Stage 1 / 3
BM25 Lexical Top-3
#1 ERR_409 Guide
#2 API Retry Spec
#3 Status Codes
Dense Semantic Top-3
#1 Conflict Handling
#2 API Retry Spec
#3 Rate Limit FAQ
RRF Fused Winner ★
#1 API Retry Spec (0.0323)
#2 ERR_409 Guide (0.0164)
#3 Conflict Handling (0.0164)
0%
Query Broadcast
Intuition Takeaway: Use Hybrid Vector RAG for fast local retrieval; layer in GraphRAG when your queries require multi-hop entity connections across separate documents or corpus-wide thematic summaries.
Production NumPy & PyTorch Code Patterns
from collections import defaultdict, deque

# Minimal Multi-Hop Knowledge Graph Traversal (2-Hop GraphRAG Context Fetcher)
triples = [
    ("Acme", "SUPPLIED_BY", "ChipCo"),
    ("ChipCo", "LOCATED_IN", "Taiwan"),
    ("ChipCo", "AUDITED_BY", "AuditFirmX"),
    ("AuditFirmX", "FLAGGED_FOR", "ComplianceRisk"),
]
graph = defaultdict(list)
for s, r, o in triples:
    graph[s].append((r, o))

def fetch_khop_facts(start_entity: str, max_hops: int = 2) -> list[str]:
    facts, q, seen = [], deque([(start_entity, 0)]), {start_entity}
    while q:
        node, depth = q.popleft()
        if depth == max_hops: continue
        for rel, nxt in graph[node]:
            facts.append(f"({node}) -[{rel}]-> ({nxt})")
            if nxt not in seen:
                seen.add(nxt)
                q.append((nxt, depth + 1))
    return facts

print("2-hop GraphRAG context for Acme:")
for f in fetch_khop_facts("Acme", max_hops=2):
    print(" ", f)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Proposing GraphRAG for simple FAQ lookup without mentioning entity-resolution and LLM indexing costs.
Best Practice: Always note that GraphRAG adds heavy offline LLM extraction cost and entity-merging complexity, so use it selectively alongside Vector RAG.
Chapter Mastery Check (+65 XP)
Score: 0 / 1
1What is the main operational downside of GraphRAG compared to standard Vector RAG?

Apply What You Learned — Solve Matching Coding Problems