GraphRAG: Technical Foundations and Engineering Practices
Graph-based retrieval-augmented generation (GraphRAG) addresses questions that require synthesis across an entire corpus rather than retrieval of a few similar passages. This article explains its three-layer indexing architecture, global and local search workflows, integration with vector retrieval, and the engineering requirements for production deployment, including cost control, traceability, evaluation, and access isolation.
1. Why Vector Retrieval Struggles with Global Questions
Traditional retrieval-augmented generation (RAG) assumes that the information needed to answer a question exists in a few passages within a corpus. The system embeds the question, retrieves the top-K similar chunks from a vector database, and asks a large language model (LLM) to synthesize an answer.
This assumption works well for localized factual questions, such as “What did this person do?” or “What is the default value of this configuration setting?”
Many business questions, however, require a broader view:
- What are the central issues behind this collection of customer complaints?
- Which categories account for most of the risky clauses across these contracts?
- What common root causes appear in this week’s incident reviews?
The answers are not contained in any single passage. They require synthesis and comparison across the corpus.
Vector retrieval can systematically struggle with these questions. Retrieved passages may be highly similar to one another, giving the model several overlapping local perspectives without the broader structure. The resulting answer may sound reasonable but offer little useful insight.
Graph-based RAG, or GraphRAG, takes a different approach: instead of treating the corpus solely as a collection of text chunks, it first distills the information into a structured knowledge graph, then uses that structure for retrieval and synthesis.
2. Offline Indexing: Three Layers of Searchable Information
A graph-based indexing pipeline typically produces three types of searchable assets. These layers underpin the retrieval strategies that follow.
Layer 1: Text Units
A text unit is the smallest addressable segment of the source material. It retains source-location information so that conclusions can be traced back to specific passages.
This traceability is essential in enterprise settings: final conclusions should remain connected to their underlying evidence.
Layer 2: Entities and Relationships
Information extraction identifies entities—such as people, organizations, equipment, metrics, and contract clauses—and relationships between them.
The pipeline also aggregates an entity description from evidence across multiple text units. Unlike an individual chunk, this description is a multi-source summary. Its cross-document perspective is one source of the system’s broader synthesis capability.
Layer 3: Communities and Community Reports
Community detection runs on the entity relationship graph to identify hierarchical groups. Leiden is a commonly used algorithm for this purpose, including configurations based on modularity optimization.
An LLM then generates a structured report for each community. Reports typically describe its entities, themes, key findings, and supporting evidence.
A community report is effectively a searchable summary of a broader portion of the corpus.
The following pseudocode illustrates the indexing stages:
# Pseudocode: illustrates pipeline stages, not a specific product APIdef build_index(corpus):units = split_to_text_units(corpus) # 1. Split text and preserve sourcesgraph = extract_graph(units) # 2. Extract entities, relationships, and claimsfor entity in graph.entities: # 3. Aggregate multi-source descriptionsentity.summary = summarize(entity.evidence)communities = detect_communities(graph, method="leiden")reports = [summarize_community(c) for c in communities] # 4. Generate community reportsreturn Index(units, graph, communities, reports,entity_vectors=embed([e.summary for e in graph.entities]))
Indexing is computationally intensive. A production implementation should support incremental updates so that new documents trigger rebuilding of affected entity descriptions and community reports rather than unnecessary full reprocessing. Intermediate artifacts should be persisted in object storage to avoid the cost of repeated extraction.
3. Global Search: Map-Reduce Synthesis
Global search operates on community reports rather than directly retrieving source passages. It follows a map-reduce pattern: answer the question separately over selected reports, then combine the partial results.
The workflow has three stages:
- Select relevant community reports based on the question, using community level, topic similarity, or a predefined sampling strategy.
- Query each selected report independently to generate a scored partial answer.
- Merge the partial answers into a consolidated response with source identifiers.
def global_search(question, reports, k):selected = rank_reports(question, reports)[:k]partials = [llm(f"Answer the question using the following report and assign an importance score from 0 to 100:\n{r}\nQuestion: {question}")for r in selected]return llm(f"Merge the following scored partial findings, remove duplicates, and produce a unified answer:\n{partials}")
This approach converts a task that exceeds a single context window into distributed synthesis that can be parallelized and managed within a budget.
The trade-off is that the number of report-level model calls grows linearly with the number of selected communities. Report filtering, hierarchy pruning, and result caching are therefore important cost controls.
4. Local Search: Six-Step Combined Retrieval
Local search targets questions about specific entities. It uses entities as anchors for retrieving several complementary types of context.
The process can be divided into six steps:
- Embed the question. Generate a query vector.
- Map the query to entities. Search the entity-description vector space for candidate entities. Moderate oversampling helps compensate for differences in description granularity.
- Load conversation history. Build a separate context block from recent turns to help resolve references.
- Retrieve related community reports. Add the broader thematic context surrounding the selected entities.
- Retrieve relationships and claims. Include relationship edges and extracted assertions with subjects and temporal information, providing structured evidence about who did what to whom.
- Retrieve associated text units. Follow the entities back to source passages for evidence closest to the original material.
The system then assembles these heterogeneous context blocks using fixed delimiters and explicit token budgets. The model generates an answer with evidence identifiers attached to individual conclusions.
def local_search(query, index, top_k=10, max_tokens=8000):q_vec = embed(query)entities = map_query_to_entities(q_vec, index.entity_vectors, k=top_k, oversample=2)history = build_history_context(max_turns=3, max_tokens=1000)ctx = assemble(history,reports=[index.report_of(e) for e in entities],relations=[index.relations_of(e) for e in entities],claims=[index.claims_of(e) for e in entities],units=[index.units_of(e) for e in entities],delimiter="\n---\n", max_tokens=max_tokens)return llm(f"{ctx}\n\nQuestion: {query}\nRequirement: Cite evidence identifiers for each conclusion.")
5. GraphRAG and Vector Retrieval: Complementary Roles
Graph-based retrieval and vector retrieval are not mutually exclusive. A mature implementation typically uses hybrid routing based on the type of question:
- Localized factual questions: Use vector or keyword retrieval for low latency.
- Corpus-wide synthesis questions: Use community reports.
- Entity-centered questions: Use graph-based retrieval across multiple context sources.
Within this architecture, the vector database supports nearest-neighbor search over entity descriptions, while the graph supports structural expansion. A shared context-assembly layer brings the retrieved information together.
6. Production Requirements and Common Pitfalls
Extraction Quality Sets the Ceiling
Errors in entity and relationship extraction can propagate through the graph. Establish sampled human review and confidence thresholds to control extraction quality.
Manage Budgets Explicitly
Context assembly needs token limits and clear priorities. When the available evidence is insufficient, the system should decline to answer rather than produce an unsupported conclusion.
Make Retrieval Observable
Log retrieved entities, selected communities, stage-level latency, and token consumption. Integrate these signals with monitoring and alerting so that teams can distinguish retrieval failures from generation failures.
Evaluate Local and Global Questions Separately
Local-question evaluation should focus on retrieval hit rate and answer faithfulness. Global-question evaluation should assess coverage of conclusions and consistency of key findings.
A single evaluation metric cannot adequately capture both behaviors.
Preserve Permissions and Tenant Isolation
Graphs and reports must inherit access controls from the source documents. Multi-tenant systems need index-level partitioning to prevent unauthorized retrieval.
For cloud deployment, these requirements map to general infrastructure categories:
- Object storage for indexing artifacts
- Container platforms for extraction and indexing jobs
- Vector search services for nearest-neighbor entity retrieval
- Logging and monitoring systems for observability
Baidu AI Cloud has corresponding product categories that can be considered when selecting the underlying infrastructure. This does not imply that every relevant service is available in every region.
7. Limitations and Future Directions
GraphRAG increases indexing cost and pipeline complexity, and community detection results can be sensitive to parameter choices.
Potential directions for further development include:
- Adding temporal validity and conflict resolution to the claims layer
- Supporting on-demand drill-down through community hierarchies
- Moving from rule-based retrieval routing to learned routing models
- Explicitly representing multi-hop reasoning as graph path search
For engineering teams, the practical starting point is a pilot focused on problems that genuinely require corpus-wide synthesis. Measurable improvements should determine whether the approach is expanded to a broader set of workloads.
