AI Wiki中文/EN

GraphRAG: asking about a whole collection

图增强检索生成

Group an authored graph, retain bridge evidence and compare local retrieval with global coverage.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

“What does this whole collection discuss?”

Finding the opening time of Orion requires a small piece of evidence. Asking which themes connect an entire collection is different: the nearest few passages may all concern one popular exhibit and miss the rest. A system needs a way to organize and combine evidence beyond one local neighborhood.

GraphRAG can broadly refer to retrieval-augmented systems that use graphs. This article focuses on the 2024 Local to Global paper’s specific approach: extract entities and relationships, summarize graph elements, detect hierarchical communities, prepare community reports and combine query-focused answers across those reports. It is not merely “put a knowledge graph next to a language model.” GraphRAG, sections 2.1–2.6

The earlier RAG model retrieves passages as latent evidence for a generator. Community-based global summarization changes how evidence is organized and gathered; it need not implement the original RAG-Sequence objective. RAG, section 2.1 Before building a graph, compare direct keyword or passage retrieval for local questions, and a source-text summarization baseline for global questions.

A complete node partition can still lose bridge evidence during aggregation.
A complete node partition can still lose bridge evidence during aggregation.

The graph is already a compressed interpretation

Extraction turns text into entity and relationship instances. Name resolution merges references; summaries compress descriptions. Every stage can omit a qualifier or join unrelated entities. The paper uses an undirected weighted graph and Leiden community detection to obtain hierarchical partitions. Its rich textual element summaries differ from a strictly normalized triple-only knowledge graph. GraphRAG, sections 2.2–2.4

To study grouping without invoking an LLM, our original six-node example assigns a symmetric weighted adjacency matrix A with no self-loops. Define weighted degree and total edge weight:

ki=∑jAij,m=12∑iki.k_i=\sum_j A_{ij},\qquad m=\frac12\sum_i k_i.

We choose modularity as an explicit grouping objective. For group labels c, it compares within-group edge weight with a degree-based null expectation:

Q(c)=∑g[Lgm−(Kg2m)2].Q(c)=\sum_g\left[\frac{L_g}{m}-\left(\frac{K_g}{2m}\right)^2\right].

Lg is the weight of internal undirected edges counted once, and Kg is the sum of weighted degrees in group g. Our code defines Q=0 for an edgeless graph. This is a teaching objective chosen here, not a claim that our exhaustive solver implements the paper’s Leiden pipeline.

For six nodes we can enumerate all distinct set partitions and select the best:

c∗=arg max⁡c∈Π6Q(c),∣Π6∣=203.c^*=\operatorname*{arg\,max}_{c\in\Pi_6}Q(c),\qquad |\Pi_6|=203.

Two triangles have edge weight 3; a single bridge between them has weight 1. Total edge weight is 19, each triangle has internal weight 9 and degree sum 19. Splitting into the triangles gives modularity 17/38, while putting everything in one group gives zero.

In the paper, community summaries become inputs to query-focused intermediate answers, which are ranked and combined under a context budget. A schematic description is:

ug=Answer⁡(q,Report⁡(g)),y=Reduce⁡(q,{ug}g∈S).u_g=\operatorname{Answer}(q,\operatorname{Report}(g)),\qquad y=\operatorname{Reduce}(q,\{u_g\}_{g\in S}).

The paper shuffles reports into chunks, generates intermediate answers and helpfulness scores, filters zero-scored answers and assembles a final context. Our code stops at structured community evidence; it performs no natural-language report generation or answer synthesis. GraphRAG, sections 2.5–2.6

For the authored graph, we can at least measure whether aggregation retains source identifiers:

SourceCoverage⁡=∣Sretained∩Sgraph∣∣Sgraph∣.\operatorname{SourceCoverage}=\frac{|S_{\mathrm{retained}}\cap S_{\mathrm{graph}}|}{|S_{\mathrm{graph}}|}.

This measures source-ID coverage in the existing graph. It does not prove coverage of the original documents, correct extraction, or a faithful generated answer.

Six nodes, two groups and one easy-to-lose bridge

Run the Python 3.12 standard-library program. Nodes A–F and source IDs s1–s7 are authored fixtures; weights are assigned for the exercise, not inferred from documents. The solver enumerates partitions using canonical group labels, avoiding duplicate relabelings. It rejects more than eight nodes because exhaustive partition search grows rapidly.

"""Original exhaustive modularity grouping for six authored nodes; no Leiden/LLM."""
import json

NODES = ['A','B','C','D','E','F']
EDGES = [('A','B',3,'s1'),('A','C',3,'s2'),('B','C',3,'s3'),('D','E',3,'s4'),('D','F',3,'s5'),('E','F',3,'s6'),('C','D',1,'s7')]


def partitions(n):
    if not isinstance(n,int) or n < 1 or n > 8:
        raise ValueError('enumeration restricted to 1..8 nodes')
    def grow(labels):
        if len(labels)==n:
            yield tuple(labels); return
        for label in range(max(labels)+2):
            yield from grow(labels+[label])
    yield from grow([0])


def modularity(nodes, edges, labels):
    if len(set(nodes)) != len(nodes) or len(labels) != len(nodes):
        raise ValueError('distinct nodes and one label per node required')
    degree = dict.fromkeys(nodes,0.); m = 0.; internal = {}
    group = dict(zip(nodes,labels))
    for a,b,w,source in edges:
        if a not in group or b not in group or a==b or not isinstance(w,(int,float)) or not 0 < w < float('inf'):
            raise ValueError('positive finite non-loop edges required')
        degree[a] += w; degree[b] += w; m += w
        if group[a]==group[b]:internal[group[a]]=internal.get(group[a],0)+w
    if m == 0:return 0.
    return sum(internal.get(c,0)/m-(sum(degree[n] for n in nodes if group[n]==c)/(2*m))**2 for c in set(labels))


def communities(nodes=NODES, edges=EDGES):
    candidates = list(partitions(len(nodes)))
    best = max(candidates,key=lambda p:modularity(nodes,edges,p))
    return best, modularity(nodes,edges,best), len(candidates)


def aggregate(labels, nodes=NODES, edges=EDGES):
    group = dict(zip(nodes,labels)); result = []
    for label in sorted(set(labels)):
        members = [n for n in nodes if group[n]==label]
        # Keep bridge sources too; community summaries alone may hide them.
        internal = [s for a,b,w,s in edges if a in members and b in members]
        bridges = [s for a,b,w,s in edges if (a in members)!=(b in members)]
        result.append(dict(members=members,internal_sources=internal,bridge_sources=bridges))
    return result


def demo():
    labels,q,count = communities()
    groups = aggregate(labels)
    local_sources = [s for a,b,w,s in EDGES if a=='A' or b=='A']
    global_sources = sorted(set(s for g in groups for key in ['internal_sources','bridge_sources'] for s in g[key]))
    return dict(nodes=NODES,edges=EDGES,labels=labels,modularity=q,partitions=count,communities=groups,
                local_sources=local_sources,global_sources=global_sources,source_coverage=[len(local_sources)/len(EDGES),len(global_sources)/len(EDGES)])


if __name__ == '__main__':
    print(json.dumps(demo(), allow_nan=False))

The best partition is ABC and DEF, with Q≈0.447368. A local lookup around A returns s1 and s2, covering 2/7 of this graph’s sources. Aggregating both groups’ internal and bridge source lists retains all seven. Keeping only internal edges would lose s7, even though every node still belongs to a group. The example therefore separates complete node assignment from complete relation evidence.

aggregate returns structured member and source lists. Those are auditable inputs for a future report generator, not automatically extracted entities or fluent summaries. A production implementation would need to preserve the connection from each graph fact to a source version and text span, then verify the generated report against those spans.

The number of partitions is the Bell number, which grows far too quickly for corpus-scale enumeration. Our modularity routine also scans group memberships when computing degree totals. Its purpose is a tiny, exactly checkable optimum; it is not a scalable alternative to Leiden. The original method’s model calls, extraction cost and report token budgets are absent from the runtime measured here.

A beautiful partition can summarize an incomplete graph

A complete partition covers the nodes that were extracted, including any duplicate or mistaken nodes. It cannot recover a relationship never extracted. Community reports can lose minority themes, uncertainty and cross-community bridges; combining their answers can repeat those omissions. A high modularity score assesses graph organization under one objective, not answer truth or relevance.

For evaluation, separate local fact lookup from global synthesis. Audit extraction and entity merges; compare answers under equal context budgets; inspect source-supported claims and missing themes. Querying all community reports may improve coverage but cost more than a local lookup. Index updates can invalidate entity summaries, community assignments and higher-level reports, so track dependencies instead of refreshing only the changed vector.

Graph structure is useful when relationships and collection-wide organization matter. It adds little when an exact ID lookup already answers the question. Use uncertainty and direct source links when extraction or summarization is unreliable.

Look for what falls between the groups

  1. Explain. Why is “every node belongs to a community” not a completeness guarantee? Answer: Extraction may have missed facts before partitioning, and summaries may omit edges or conditions afterwards. Node coverage is only one intermediate property.
  2. Calculate. Derive modularity for the two triangles. Answer: Each contributes 9/19−(19/38) squared. Summing twice gives 18/19−1/2=17/38. The bridge affects degrees and total weight even though it is not internal.
  3. Modify. Remove bridge_sources from global aggregation. What disappears? Answer: Source s7 disappears and source coverage falls from 7/7 to 6/7, while all six nodes still occur. This is an evidence-loss bug if cross-group relations matter to the question.
  4. Investigate. How would you compare GraphRAG with passage retrieval? Answer: Use separate local and global question sets, the same source versions and answer budgets, then assess supported claims, coverage, extraction errors and total indexing/query cost. Do not infer answer quality from modularity alone.

From latent passages to collection-wide reports

Read the original RAG paper for probabilistic passage-conditioned generation and the Local to Global paper for its community-report pipeline. Our graph grouping and source aggregation reproduce neither a trained extractor nor the papers’ benchmark outcomes. RAG evaluation provides the next step: assess the answer separately from the intermediate graph.

Make a prediction, then check

Do complete node partitions guarantee complete coverage of the original text?

Choose one answer

Learning objectives

  • Distinguish graph indexing, community reports and grounded final answers.
  • Run the original example, explain its counterexample and identify the untested deployment assumptions.

Prerequisites & connections

Explore related knowledge →

References

  1. From Local to Global: A Graph RAG Approach to Query-Focused Summarization — arXiv v1
    Darren Edge; Ha Trinh; Newman Cheng; Joshua Bradley; Alex Chao; Apurva Mody; Steven Truitt; Jonathan Larson · 2024
  2. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks — arXiv v1
    Patrick Lewis; Ethan Perez; Aleksandra Piktus; Fabio Petroni; Vladimir Karpukhin; Naman Goyal; Heinrich Küttler; Mike Lewis; Wen-tau Yih; Tim Rocktäschel; Sebastian Riedel; Douwe Kiela · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author. Recorded source scopes (some exact source objects reused from earlier checks): Read PDF 1 identity and 3–5 pipeline: extraction, entity summaries, Leiden hierarchy, community summaries and map/reduce answers. No extraction model or benchmark reproduction. Read PDF 1 identity, 2 methods opening, 3 methods and 4 training/decoding; viewed PDF 3 equations. No BART/DPR training or benchmark reproduction. 5 paired equations and four explained exercises. Enumerated all203 six-node partitions; checked modularity17/38, relabel invariance, local/global sources and preserved bridge. Authored graph, no Leiden or LLM extraction.

  • Enumerated all203 six-node partitions; checked modularity17/38, relabel invariance, local/global sources and preserved bridge. Authored graph, no Leiden or LLM extraction.
  • Four computed SVG variants per topic;12 numeric/geometry tests and42 responsive cases passed. Fourteen selected final captures directly viewed. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.