🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Graph RAG: Knowledge Graphs for Retrieval

đŸŸĸ Free Lesson

Graph RAG: Knowledge Graphs for Retrieval

Flat retrieval answers questions that live inside a passage. Plenty of important questions do not: which suppliers depend on the plant that failed, how a policy changed across three revisions, what a clinical trial and a follow-up study have in common. Those need connections that no single chunk contains, and Graph RAG exists to supply them by building an explicit graph of entities and relationships alongside your documents, then querying it with the same rigor you would give a database. The trade is clear up front — ingestion gets slower and more expensive, queries get more expressive, and answers can finally cite structure rather than proximity.

Where Flat Chunking Runs Out of Road

Chunking destroys context by design: it keeps each piece small enough to embed, which means it severs the relationships that gave the piece meaning. When a question spans those severed edges, similarity search offers the illusion of coverage — you retrieve passages that mention the right nouns while missing the fact that connects them.

The signals that you have crossed the line are specific. Answers that need aggregation across many entities, such as counting every vendor in a risk tier, exhaust the context window and still lose items. Multi-hop questions, where the answer depends on following two or three links, depend on retrieval ordering that similarity does not guarantee. Questions about change over time require linking revisions that sit in different documents. And provenance requests — show me the chain behind that claim — need edges, not a pile of loosely related text.

Graph RAG does not replace vector search; it complements it. Entities, passages and summaries usually all get embedded, and the query planner picks a route based on question shape.

Building the Graph: Extraction and Normalization

Extraction is a language model task with database discipline applied afterward. The model proposes entities, types and relations as structured output; your code is responsible for canonicalization, because every corpus contains three spellings of the same vendor and a graph that treats them as distinct nodes answers questions incorrectly with great confidence.

python
import json
import openai

client = openai.OpenAI()

EXTRACTION_SCHEMA = {
    "type": "object",
    "properties": {
        "entities": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "type": {"type": "string", "enum": ["person", "org", "product", "policy", "event", "location"]},
                    "description": {"type": "string"},
                },
                "required": ["name", "type", "description"],
            },
        },
        "relations": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "source": {"type": "string"},
                    "target": {"type": "string"},
                    "predicate": {"type": "string"},
                },
                "required": ["source", "target", "predicate"],
            },
        },
    },
    "required": ["entities", "relations"],
}

def extract_from_passage(passage: str) -> dict:
    r = client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0,
        response_format={"type": "json_schema", "json_schema": {"name": "graph", "schema": EXTRACTION_SCHEMA}},
        messages=[
            {"role": "system", "content": (
                "Extract entities and relations from the passage. Use canonical "
                "short names. Only include relations explicitly supported by the text."
            )},
            {"role": "user", "content": passage},
        ],
    )
    return json.loads(r.choices[0].message.content)

def canonical_id(name: str, alias_map: dict) -> str:
    key = name.strip().lower().replace(".", "").replace(",", "")
    if key in alias_map:
        return alias_map[key]
    parts = key.split()
    if len(parts) > 1 and any(len(p) <= 3 for p in parts):
        return "-".join(parts[:2])
    return key.replace(" ", "-")

alias_map = {"acme corp": "acme", "acme corporation": "acme", "acme inc": "acme"}
print(canonical_id("Acme Corp.", alias_map))

Two extraction mistakes cause most quality problems. Greedy extraction that records every noun produces a hairball where nothing stands out, so restrict the model to entities that carry decisions or relationships. And relations without provenance are unverifiable, so store the passage identifier on every edge — it is what lets an answer cite the sentence a relationship came from.

Community Summaries: Precomputing the Big Picture

Global questions such as "what are the main themes across these filings?" are the hard case, because the answer is distributed over the whole graph. The standard technique clusters the graph into communities — groups of densely connected nodes such as a project team or a product line — and summarizes each community once at ingestion time. Answering then becomes a two-level operation: retrieve the relevant community summaries for the theme, then descend into specific entities for detail.

Question shapeRetrieval routeWhy
Specific entity lookupVector or keyword to node, then neighborsFast, precise
Relationship questionTraverse edges between known endpointsStructure is the answer
Multi-hop chainAlternating search and traversalSimilarity alone cannot sequence hops
Global theme or summaryCommunity summaries, then descendAggregation across the whole corpus
Temporal changeVersioned nodes with time filtersRevisions are edges too

Summaries are cacheable artifacts keyed by community and document version, which is what makes the approach affordable: you pay for language model calls once per change instead of once per question.

Answering: Local Detail and Global Themes

Local questions follow a predictable path: resolve the named entities, pull their immediate neighborhood, rank the connected facts by relation type, and hand the result to the generator as a compact fact list. Global questions take the summary route. The planner decides between them from the question itself, and the decision is worth logging because misrouted questions are the most common source of confident, unsourced answers.

python
def local_answer(question: str, graph, embedder, llm) -> str:
    entities = resolve_entities(question, graph, embedder)
    facts = []
    for node in entities[:3]:
        for edge in graph.neighbors(node, limit=12):
            facts.append(f"{edge.source} -[{edge.predicate}]-> {edge.target}")
    if not facts:
        return "No connected facts found for the named entities."
    context = "\n".join(facts)
    return llm.complete(
        question,
        system="Answer only from the facts. Cite entity names for each claim.",
        context=context,
    )

def global_answer(question: str, graph, llm) -> str:
    summaries = graph.community_summaries(top_k=8, query=question)
    picked = llm.complete(
        question,
        system="Select the communities relevant to the question. Return indices only.",
        context="\n".join(f"[{i}] {s}" for i, s in enumerate(summaries)),
    )
    detail = graph.expand_communities(picked, limit=20)
    return llm.complete(
        question,
        system="Synthesize a thematic answer. Attribute each theme to its community.",
        context="\n".join(summaries[i] for i in picked) + "\n\nDetails:\n" + detail,
    )

print(local_answer("Who approves changes to the refund policy?", graph, embedder, llm))
print(global_answer("What are the recurring risks across our vendor contracts?", graph, llm))

Notice that both routes end in generation with structured evidence rather than free recall. The generator's job is synthesis and phrasing; the graph's job is being right.

Where the Graph Lives

Storage choice shapes everything downstream, and the practical options form a spectrum rather than a ranked list. A dedicated graph database gives you traversal queries, pattern matching and usually vector search in one engine, at the cost of another system to operate. A relational database with recursive queries covers moderate depth with the operational simplicity of SQL you already run. A document store keeps nodes and edges as JSON, which is flexible but pushes query logic into application code. And an in-process library is entirely reasonable when the corpus fits in memory and the product is a single service.

StoreStrengthCostChoose it when
Native graph databaseMulti-hop traversal, pattern queriesNew operational surfaceRelationship questions dominate
Relational with recursive SQLTransactions, joins with your dataDepth limits, verbose queriesYou already run SQL well
Document storeFlexible schema, easy writesQueries live in codeStructure varies by document type
Embedded libraryZero infrastructureSingle-process onlyPrototypes and small corpora

Whichever you pick, keep identifiers stable and edges typed, and store passage references so every relationship remains traceable to source text.

Cost, Freshness and the Cases to Avoid

Graph construction is the expensive half. Extraction runs a language model over every passage, canonicalization needs review when entities multiply, and community detection must be recomputed as the corpus grows. Budget for ingestion as a pipeline with statuses and retries rather than a script, and version the graph so a bad extraction batch can be rolled back without rebuilding from zero.

Freshness follows the same logic. Documents that change daily fight against community summaries computed weekly, so decide an explicit staleness budget per source: reference material can lag, incident reports cannot. Where freshness matters more than structure, keep the vector index authoritative and let the graph lag as enrichment.

The technique is also wrong for some problems. If questions consistently resolve inside a single paragraph, a graph buys complexity with nothing in return. If your corpus is unstructured prose with few entities and fewer relations, extraction quality will be poor and the maintenance burden permanent. And if nobody can state which questions currently fail, build the evaluation set first — a graph is not a substitute for knowing what your users actually ask.

Common Mistakes

Extracting every noun into a node

Fix: Constrain extraction to entities that carry decisions or relationships

Storing edges without source passage references

Fix: Attach the passage id to every relation so answers stay verifiable

Rebuilding the graph on every document update

Fix: Version nodes and recompute affected communities only

Routing every question through traversal

Fix: Plan by question shape: entity, relation, multi-hop, or global theme

Adopting Graph RAG before logging real failures

Fix: Label which questions flat retrieval already answers correctly

Key Takeaways

  • Graph RAG earns its cost on multi-hop, aggregation and provenance questions
  • Canonicalization decides answer quality more than the graph database does
  • Community summaries make global questions affordable by precomputing once
  • Local and global routes are planned per question and logged for diagnosis
  • Keep vectors authoritative for freshness-sensitive corpora; let the graph enrich
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement