Where flat chunk retrieval runs out of road
Semantic search over text chunks answers questions whose evidence sits in one place. Ask "which vendors supply the component that failed in the recall notice?" and the answer is not a passage â it is a chain: the notice names a product, the product's bill of materials names a supplier, and the supplier's contract names a region. Vector similarity will retrieve the notice and perhaps the contract, but it has no mechanism for following the chain, and stuffing every hop into the context window is neither cheap nor reliable.
Graph RAG addresses exactly this class of question by storing knowledge as entities connected by typed relationships, then traversing that structure at query time. The retrieval unit is no longer a chunk of text; it is a neighbourhood, a path, or a pre-computed community summary. Questions about "who depends on what", "what changed since the last release", and "how do these three teams interact" become pattern matching instead of similarity search.
The trade-off is construction cost. Building a trustworthy graph means extracting entities and relations from untyped prose, resolving duplicates, and keeping the result fresh â work that a pure vector pipeline never has to do. Graph RAG therefore pays off when your query mix is dominated by relational questions and your corpus has stable, identifiable entities. If most questions are definitional or procedural, conventional RAG remains the better investment.
Building the graph: entities, relations, and provenance
Extraction is a hybrid job. A named-entity model is fast and cheap for the first pass, catching people, organisations, products, and locations with predictable precision. It is weak at relations, which is where a language model earns its cost: given the sentence and the candidate entities, it emits structured triples with a relation type and optional attributes. Run both, then reconcile.
Resolution is the step teams skip and regret. "Acme Corp", "ACME Corporation", and "Acme" must collapse into one node, or traversal returns fragmented paths and every answer needs an apology. Blocking on normalised names plus fuzzy matching, with a human queue for low-confidence merges, keeps the graph honest without demanding perfection.
Every node and edge should carry provenance: the source document, the extraction timestamp, and a confidence score. Provenance serves two purposes. It lets an answer cite the sentence a relation came from, which users of factual systems expect. And it enables expiry: relations extracted from a document that has been superseded can be retired instead of accumulating into a graph nobody trusts.
from dataclasses import dataclass, field
@dataclass
class Triple:
subject: str
relation: str
obj: str
provenance: str
confidence: float = 1.0
attributes: dict = field(default_factory=dict)
class KnowledgeGraphBuilder:
def __init__(self, ner, llm, normalizer):
self.ner = ner
self.llm = llm
self.normalizer = normalizer
self.nodes = {}
self.edges = []
def ingest(self, text: str, source: str) -> int:
mentions = self.ner.find(text)
canonical = {m.text: self.normalizer.resolve(m.text) for m in mentions}
for name, node_id in canonical.items():
self.nodes.setdefault(node_id, {"name": name, "sources": set()})
self.nodes[node_id]["sources"].add(source)
triples = self._extract_relations(text, list(canonical.values()))
for triple in triples:
triple.provenance = source
self.edges.append(triple)
return len(triples)
def _extract_relations(self, text: str, entities: list[str]) -> list[Triple]:
prompt = (
"Extract relationships between the listed entities in the text. "
"Return a JSON array of objects with keys subject, relation, object, "
"confidence. Use only relations stated or directly implied.\n\n"
f"Entities: {', '.join(entities)}\n\nText:\n{text[:3000]}\n\nRelations:"
)
raw = self.llm.generate(prompt)
return [Triple(**t) for t in self._parse_json_array(raw)]
Ask for relations "stated or directly implied" and reject everything else. Models over-extract when invited to speculate, and a single speculative edge can invent a dependency that operations then chases for a week.
Storing and querying with Cypher
A property graph database such as Neo4j stores nodes, typed edges, and key-value properties, and Cypher expresses traversal as patterns. The pattern (:Alert)-[:CAUSED_BY]->(:Deploy)-[:AFFECTS]->(:Service) is the whole query: find alerts, follow their cause to a deployment, and see which services that deployment touched. Parameterise every value and whitelist relation types; interpolated labels are how a retrieval layer becomes an injection surface.
Index the properties you filter on â node names, timestamps, source identifiers â and cap traversal depth. An unbounded neighbourhood query on a dense hub node can return tens of thousands of paths and stall the request. Depth two or three covers most real multi-hop questions; anything deeper is usually better answered by a pre-computed summary.
Multi-hop retrieval at request time
The retrieval flow has three steps. Extract the salient entities from the user's question, either with the same named-entity model or with a constrained generation prompt. Traverse from each entity for a bounded number of hops, collecting nodes, edges, and any linked text snippets. Then run a conventional vector search over the same corpus and merge the two result sets.
The merge deserves care. Graph results are precise but narrow; vector results are broad but noisy. Deduplicate by provenance, order graph results before vector results when the question named a specific entity, and truncate against a token budget rather than a fixed result count, so long edges do not push the decisive path out of context.
class HybridGraphRetriever:
def __init__(self, graph_store, vector_store, entity_extractor, max_hops: int = 2):
self.graph = graph_store
self.vector = vector_store
self.entities = entity_extractor
self.max_hops = max_hops
def retrieve(self, query: str, token_budget: int = 3000) -> dict:
named = self.entities.extract(query)
graph_hits = []
for entity in named:
paths = self.graph.neighbours(entity, depth=self.max_hops, limit=25)
graph_hits.extend(paths)
vector_hits = self.vector.search(query, top_k=8)
seen, merged = set(), []
for item in self._order(named, graph_hits, vector_hits):
key = item.get("provenance") or item.get("id")
if key in seen:
continue
seen.add(key)
merged.append(item)
context, spent = [], 0
for item in merged:
text = item.get("text", "")
if spent + len(text) > token_budget:
break
context.append(item)
spent += len(text)
return {"entities": named, "context": context, "truncated_at": spent}
def _order(self, named, graph_hits, vector_hits):
if len(named) >= 2:
return graph_hits + vector_hits
return vector_hits + graph_hits
The routing rule is deliberately simple: two or more named entities means the question is relational and graph results lead; otherwise vector similarity leads. Log which source supplied the winning context so the heuristic can be re-tuned from data rather than debate.
Community summaries for corpus-level questions
Some questions are not about an entity at all â "summarise the main themes in this knowledge base" cannot be answered by any single neighbourhood. The standard technique is to detect communities of densely connected nodes offline (Louvain or similar), generate a short summary per community, and index those summaries for retrieval at query time. The answer is then assembled from community summaries first, with path-level detail added for whichever entities the question touches.
This runs as a batch job on a schedule, not per request. Community structure changes slowly; recomputing it nightly is ample, and the summaries give corpus-level questions an entry point that traversal alone cannot provide.
Hybrid graph and vector retrieval
Neither store is complete on its own, so production systems run both. A practical routing heuristic: if the question names two or more known entities, or contains relation words such as "depends on", "manages", or "acquired", weight the graph results first; otherwise let vector similarity lead and use the graph only to enrich whatever entities appear in the top passages. Always attach provenance links to whichever results win, because the user's next question is "where did that come from".
| Aspect | Vector RAG | Graph RAG |
|---|---|---|
| Retrieval unit | Text chunk | Entity neighbourhood |
| Multi-hop questions | Poor | Native strength |
| Construction cost | Low | High |
| Freshness cost | Re-embed changed docs | Re-extract and resolve |
| Corpus summaries | Not inherent | Community summaries |
| Best fit | Definitional and procedural QA | Relational and comparative QA |
When Graph RAG is the wrong choice
Three signals say to stop. Your entity extractor cannot hold acceptable precision on the corpus â every downstream answer inherits the error. Your questions rarely mention concrete entities, leaving traversal with nothing to start from. Or your corpus turns over so fast that the graph is permanently stale relative to the vector index built beside it. In each case, invest in better chunking and hybrid vector retrieval first; add the graph when the relational query share is large enough to justify keeping a second store fresh.
Common Mistakes
Building the graph without provenance on nodes and edges
Fix: Record source document, timestamp, and confidence on every triple so answers can cite and relations can expire.
Skipping entity resolution and accepting surface-form duplicates
Fix: Normalise and fuzzy-match names into canonical nodes, with a human queue for ambiguous merges.
Allowing unbounded traversal depth at query time
Fix: Cap hops at two or three and answer deeper questions from pre-computed community summaries.
Applying Graph RAG to a corpus with no stable entities
Fix: Measure entity extraction precision and relational query share before committing to a graph store.
Key Takeaways
- Graph RAG replaces similarity over chunks with traversal over entities, which is what multi-hop questions actually require.
- Extraction is hybrid: a named-entity pass for speed, a model pass for relations, and a resolver to merge surface forms.
- Provenance on every edge enables citation and expiry â the two properties that keep a graph trustworthy over time.
- Bound traversal depth and parameterise Cypher; unbounded patterns and interpolated labels are the two classic production hazards.
- Community summaries computed offline are the entry point for corpus-level questions that no single neighbourhood can answer.
- Run graph and vector retrieval together with routing heuristics rather than choosing one store for the whole query mix.