Graph RAG
Graph RAG
RAG that uses a knowledge graph. Improves retrieval quality by leveraging relationships between entities.
Graph RAG
RAG that uses a knowledge graph. Improves retrieval quality by leveraging relationships between entities.
Graph RAG is an advanced retrieval-augmented generation technique that combines a Knowledge Graph with conventional RAG (Retrieval-Augmented Generation). While general RAG retrieves using only the vector similarity of document chunks, Graph RAG structures entities and the relationships between them to retrieve more accurate and relevant information. This enables it to answer effectively even complex questions that require multi-hop reasoning.
The core components of Graph RAG are knowledge graph construction, which extracts entities and relationships from documents, graph-based retrieval, and community summarization. First, an LLM is used to extract triples in the form (subject, relation, object) from documents to build a knowledge graph. During retrieval, entities related to the query are found, and connected information is fetched together through graph traversal. Microsoft's GraphRAG additionally detects communities with the Leiden algorithm and generates a summary of each community to use for global search.
Graph RAG shows better performance than conventional RAG especially for relationship queries such as "What is related to what, and how?", queries that require synthesizing information across multiple documents, and summary queries over an entire dataset. For example, it is effective for questions that require multi-step relationship reasoning, such as "What other companies has the CEO of Company A invested in?"
For implementation, you can combine a graph database such as Neo4j or Amazon Neptune with a vector store, or use LlamaIndex's KnowledgeGraphIndex or Microsoft's GraphRAG library. However, building a knowledge graph requires many LLM calls, so the initial indexing cost is high, and since graph quality directly affects retrieval performance, the accuracy of entity/relationship extraction is important.
This is a simple Graph RAG implementation example using LlamaIndex.
# pip install llama-index llama-index-llms-openai llama-index-graph-stores-neo4j
import os
from llama_index.core import (
SimpleDirectoryReader,
KnowledgeGraphIndex,
Settings,
StorageContext
)
from llama_index.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.graph_stores.neo4j import Neo4jGraphStore
os.environ["OPENAI_API_KEY"] = "your-api-key"
# LLM 및 임베딩 설정
Settings.llm = OpenAI(model="gpt-4o-mini", temperature=0)
Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small")
# 문서 로드
documents = SimpleDirectoryReader("./data").load_data()
# Neo4j 그래프 스토어 연결 (로컬 또는 Aura)
graph_store = Neo4jGraphStore(
username="neo4j",
password="your-password",
url="bolt://localhost:7687",
database="neo4j"
)
storage_context = StorageContext.from_defaults(graph_store=graph_store)
# 지식 그래프 인덱스 생성 (엔티티/관계 자동 추출)
kg_index = KnowledgeGraphIndex.from_documents(
documents,
storage_context=storage_context,
max_triplets_per_chunk=10, # 청크당 최대 트리플 수
include_embeddings=True, # 벡터 검색도 함께 활용
show_progress=True
)
# 쿼리 엔진 생성
query_engine = kg_index.as_query_engine(
include_text=True, # 원본 텍스트도 포함
response_mode="tree_summarize",
embedding_mode="hybrid", # 그래프 + 벡터 하이브리드
similarity_top_k=5
)
# 그래프 RAG 질의
response = query_engine.query(
"삼성전자의 주요 협력사들과 그들 간의 관계를 설명해주세요."
)
print("=== 그래프 RAG 응답 ===")
print(response)
# 추출된 트리플 확인
print("\n=== 추출된 지식 그래프 트리플 (샘플) ===")
for node in list(kg_index.index_struct.table.values())[:5]:
print(f"- {node}")
# 결과 예시:
# === 그래프 RAG 응답 ===
# 삼성전자의 주요 협력사로는 TSMC, SK하이닉스, 퀄컴 등이 있습니다.
# TSMC는 삼성전자와 반도체 파운드리 시장에서 경쟁 관계이며...
#
# === 추출된 지식 그래프 트리플 (샘플) ===
# - (삼성전자, 경쟁사, TSMC)
# - (삼성전자, 공급, 애플)
# - (SK하이닉스, 협력, 삼성전자)
Graph RAG has a higher indexing cost than conventional vector RAG, but it provides better answer quality for complex queries.
| Item | Vector RAG | Graph RAG (Local) | Graph RAG (Global) |
|---|---|---|---|
| Indexing cost (1MB document) | $0.01~0.02 | $0.50~2.00 | $0.50~2.00 |
| Query cost | $0.01~0.03 | $0.02~0.05 | $0.10~0.50 |
| Query latency | 1–3 sec | 2–5 sec | 5–15 sec |
| Simple factual query accuracy | High | High | Moderate |
| Multi-hop reasoning accuracy | Low | High | High |
| Global summary quality | Low | Moderate | Very high |
Cost optimization tips: