GraphRAG and Hybrid Graph Retrieval
When answers depend on connections or on a whole collection, add structure to retrieval. How it works, what it costs and when to skip it.
GraphRAG extracts entities and relationships from documents, organizes them into a graph and uses that structure to retrieve evidence. It helps with two kinds of question that passage search handles poorly: those that connect facts across documents and those about themes in an entire collection. It costs more to build and maintain, so start with ordinary hybrid retrieval and add a graph only for question types where tests show a gain.
What you will learn: why graphs help, the indexing pipeline, local and global search, a working miniature, hybrid graph and vector retrieval, costs, evaluation and security.
Prerequisites: RAG Explained and Agentic RAG and Embeddings, Vector and Hybrid Search, Reranking.
Two questions passage search misses
Connecting questions. "Which projects could be affected if the billing service fails?" The answer may be spread over several documents, none of which mentions both the failure and all the projects. Similarity search returns passages that look like the question, not the chain that answers it.
Whole-collection questions. "What are the recurring causes of incidents this year?" No single passage says so. Retrieving the top ten passages samples a tiny part of the collection.
A knowledge graph records entities (people, services, products, events) and relationships between them (depends on, owned by, caused). With those links, a system can walk from one fact to the next, and it can summarize clusters of related facts ahead of time.
Key terms
| Term | Meaning |
|---|---|
| Entity | A thing with an identity, such as a service or a supplier |
| Relationship | A typed, directed link between two entities |
| Provenance | The source passages behind a node or edge |
| Community | A group of entities more connected to each other than to the rest |
| Community report | A written summary of one community |
| Traversal | Following edges from a starting entity |
The architecture
The term is used for many designs. The best-known is the one described by Microsoft researchers in From Local to Global and released as the open-source GraphRAG project. In outline: a model extracts entities and relationships from each chunk; descriptions are merged; a community detection method (Leiden) builds a hierarchy of clusters; a model writes a report for each. Queries then use the graph in different modes.
| Mode | How it works | Suits |
|---|---|---|
| Local search | Find the entities in the question, gather neighbors, relationships and linked text | Questions about specific things |
| Global search | Ask many community reports for partial answers, then combine them (map and reduce) | Themes across the whole collection |
| DRIFT search | Local search that also uses community information to broaden and refine | Specific questions needing wider context |
| Basic search | Ordinary vector retrieval over text units | Simple lookups and a baseline |
A miniature you can run
"""A miniature GraphRAG: local lookups, community summaries, provenance."""
from collections import Counter
TRIPLES = [ # subject, relation, object, source chunk
("Atlas", "depends_on", "Billing", "c1"), ("Billing", "owned_by", "Marco", "c2"),
("Billing", "had_incident", "Timeout", "c3"), ("Atlas", "led_by", "Priya", "c4"),
("Search", "depends_on", "Indexer", "c5"), ("Indexer", "had_incident", "Timeout2", "c6"),
("Indexer", "owned_by", "Lena", "c7"),
]
neighbors = {}
for s, r, o, src in TRIPLES:
fact = f"{s} {r} {o} [{src}]"
neighbors.setdefault(s, []).append((o, fact))
neighbors.setdefault(o, []).append((s, fact))
def local_search(entity, hops=2):
facts, frontier, seen = [], [entity], {entity}
for _ in range(hops):
nxt = []
for node in frontier:
for other, fact in neighbors.get(node, []):
if fact not in facts:
facts.append(fact)
if other not in seen:
seen.add(other)
nxt.append(other)
frontier = nxt
return facts
def communities():
"""Connected groups. Real systems use a method such as Leiden."""
left, groups = list(neighbors), []
while left:
stack, group = [left[0]], set()
while stack:
node = stack.pop()
if node not in group:
group.add(node)
stack += [o for o, _ in neighbors[node]]
groups.append(group)
left = [n for n in left if n not in group]
return groups
def summarize(group):
"""A model would write prose; here we count what the facts say."""
rels = Counter(r for s, r, o, _ in TRIPLES if s in group)
hub = min(group, key=lambda n: (-len(neighbors[n]), n))
sources = sorted(src for s, _, _, src in TRIPLES if s in group)
return (f"Cluster around {hub}: {rels['had_incident']} incident(s), "
f"{rels['depends_on']} dependency(ies). Sources {sources}")
print("LOCAL: what touches Atlas within two steps?")
print("\n".join(" " + f for f in local_search("Atlas")))
print("GLOBAL: where do incidents occur?")
for g in communities():
print(" " + summarize(g))
Output:
LOCAL: what touches Atlas within two steps?
Atlas depends_on Billing [c1]
Atlas led_by Priya [c4]
Billing owned_by Marco [c2]
Billing had_incident Timeout [c3]
GLOBAL: where do incidents occur?
Cluster around Billing: 1 incident(s), 1 dependency(ies). Sources ['c1', 'c2', 'c3', 'c4']
Cluster around Indexer: 1 incident(s), 1 dependency(ies). Sources ['c5', 'c6', 'c7']
Local search starts at one project and finds its leader, its dependency and, two steps away, that dependency's owner and incident, each with the source chunk. The global view groups the graph and reports incidents per cluster. This miniature writes triples by hand and uses connected groups as communities. In a real system, extraction is done by a model with errors to catch, communities come from a proper algorithm and reports are generated prose.
Implementation steps
- Define the schema. A handful of entity and relationship types drawn from your questions.
- Extract with structure. Require a fixed output format and a supporting quotation or chunk identifier for every edge.
- Validate. Reject unknown types and edges whose evidence does not mention both ends.
- Resolve entities. Merge spelling variants and aliases using identifiers from master data where possible; send doubtful merges to review.
- Load and index. Store nodes and edges with dates and sources; embed names and descriptions for lookup.
- Query. Link question entities, traverse with limits, gather text and answer with citations.
- Update. When a document changes, remove its contributions before adding new ones, and refresh affected summaries.
Merge two different customers into one node and the graph will confidently join their facts. Fail to merge two names for one service and connections vanish. Measure both errors on a reviewed sample.
Graph and vector hybrid retrieval
Graphs and vector indexes complement each other. A practical pattern:
- Use vector or keyword search to find candidate passages and entities.
- Expand from those entities along selected relationship types, one or two steps.
- Collect the source passages behind the traversed edges.
- Fuse and rerank all passages.
- Give the model the passages, plus the relationship paths as a compact list.
| Expansion control | Why |
|---|---|
| Maximum hops | The neighborhood grows very quickly |
| Allowed relationship types | "Mentioned with" links connect almost everything |
| Limit per node | Hubs such as a company name flood results |
| Date filter | Old relationships mislead |
| Permission filter on each source | A path can cross restricted documents |
Querying a graph directly
If your graph is curated, an agent can ask precise questions in a query language such as Cypher or SPARQL, or better, through approved parameterized queries, with the same cautions as for generated SQL: read-only access, limits and verification. See Query Rewriting, Multi-Hop, SQL and Multimodal RAG.
Walking through one question
Suppose an engineer asks, "If we retire the old export service, who needs to be told?" Follow the stages and notice what can go wrong at each.
| Stage | What happens | Failure to watch |
|---|---|---|
| Link entities | "Old export service" is matched to a node, using aliases | Matches the new service with a similar name |
| Choose relationships | Follow depends-on edges backward and ownership edges | Follows loose mention links and returns half the company |
| Traverse | Up to two steps from consumers to their owners | A hub node explodes the result |
| Check validity | Drop edges that ended or have no current source | Tells a team that moved off a year ago |
| Gather text | Fetch the passages behind each edge, filtered by access | A path reveals a restricted project |
| Answer | List owners with the path and citation for each | Presents an incomplete list as complete |
The final row matters. A graph returns what it contains. If dependency data is missing for some systems, the honest answer lists what was found, says which sources were used and warns that unrecorded dependencies would not appear. Users otherwise read a tidy list as the whole truth.
Prompting for extraction
Extraction quality depends on clear definitions. For each type, give the model a one-sentence definition, two positive examples and one near miss. Tell it to leave a field empty when the text does not say, and to quote the supporting sentence. Run extraction on your labeled sample after every change to the prompt, schema or model, and compare precision and recall by type, because an improvement for one relationship often costs another.
Community summaries in practice
Summaries are generated text and inherit extraction errors. Include the identifiers of member facts in each report, set a size limit, and regenerate when membership changes noticeably. Choose the hierarchy level to match the question: broad levels give overviews, narrow levels keep detail. Test both levels on your broad questions rather than assuming that more detail is better.
What it costs
Full GraphRAG calls a language model over every chunk for extraction and again for summaries, before any user asks anything. Global search also calls the model many times per question. Microsoft Research has described LazyGraphRAG, which postpones model work to query time; it reports indexing costs equal to ordinary vector indexing and about a thousandth of full GraphRAG's. Other variants use cheaper language processing to extract. Results depend on data and questions, so estimate on a sample first.
| Cost driver | Estimate from |
|---|---|
| Extraction | Chunks times tokens per call, plus retries |
| Summaries | Number and size of communities, per hierarchy level |
| Updates | Change rate and how many communities each change touches |
| Global queries | Reports consulted per question |
| People | Schema design, entity review, debugging |
Evaluating fairly
Compare against a good baseline: hybrid retrieval with reranking and, for broad questions, a method that summarizes many documents. Split the test set into lookup, connecting and collection-wide questions.
- Check extraction precision and recall on hand-labeled passages.
- Check that cited sources actually support each claim, as in RAG Evaluation, Grounding and Debugging.
- For broad answers, have reviewers judge coverage and correctness, and verify any counts against the data. A fluent theme summary can overstate how common something is.
- Record indexing cost, query cost and latency next to quality.
Freshness and maintenance
A graph is derived data. Keep, for every node and edge, the set of supporting chunks. When a source is deleted, drop its support and remove anything left with none. Mark community reports stale when their members change, and decide how long a stale report may be served. Record validity dates where facts change over time, such as ownership.
Security
- A summary built from many documents mixes their access rules. Build separate graphs or communities per access boundary, or restrict summaries to people who may see all inputs.
- Check permissions on every edge's sources during traversal.
- Names of entities and the existence of links can be sensitive on their own.
- A planted document can add false relationships; weigh edges by source trust and require more than one source for consequential facts.
Should you use it?
An operations team wants to ask what a failing component affects. Dependencies already exist in a configuration database, so they load those edges directly and extract from incident reports only the links between incidents and components, each reviewed at first. Local search answers impact questions. They postpone global summaries until someone shows a question that needs them.
Starting small
Pick one question type, one document collection and no more than five relationship types. Review the first few hundred extracted edges by hand. That afternoon of reading shows more about whether the approach suits your material than any amount of architecture discussion, and it produces the labeled sample you need for later measurement.
Common mistakes
- Building a graph before collecting questions that need one.
- Extracting every possible relationship type.
- No provenance on edges.
- Comparing against a weak baseline.
- Forgetting updates and deletions.
- Letting summaries cross access boundaries.
Revisit the decision after the pilot. If the graph helps only one question type, consider serving just that type from it and leaving everything else on the simpler path. A narrow graph that stays accurate is worth more than a broad one that nobody maintains.
Checklist
- Target question types are written down with a baseline result.
- Entity and relationship types are few and defined.
- Every edge has evidence and a date.
- Entity resolution errors are measured.
- Traversal has hop, type and fan-out limits.
- Deletion removes unsupported nodes and stales summaries.
- Permissions apply to paths and reports.
- Indexing and query costs are tracked.
Frequently asked questions
Is GraphRAG a replacement for vector search?
No. It is an additional structure that helps certain questions. Most deployments keep text search and use the graph where it measurably helps.
Do I need a graph database?
Not to start. Tables or files hold small graphs. A graph database helps when traversals become frequent and deep.
How accurate is automatic extraction?
It varies with documents, schema and model. Measure it on your own labeled sample instead of relying on a general figure.
What about small document sets?
If the whole set fits comfortably in a request, sending it directly may answer broad questions with far less machinery.
References and further reading
- Edge et al.: From local to global, a graph RAG approach
- Microsoft GraphRAG documentation
- Microsoft Research: LazyGraphRAG
- Microsoft Research: DRIFT search
- Traag et al.: From Louvain to Leiden
Next steps
Building and Governing Knowledge Graphs
Construction, resolution and upkeep in depth.
Knowledge Graphs and Ontologies
Model types and relationships well.
RAG Evaluation, Grounding and Debugging
Prove that the graph earned its cost.