StarModel invitation
← Back to skills
extension
Category: Content & MediaAPI key requirement unconfirmed

graphrag-patterns

Implement GraphRAG patterns combining knowledge graphs with retrieval for complex reasoning. Use this skill when building RAG over interconnected data or needing relationship-aware retrieval. Activate when: GraphRAG, knowledge graph, graph retrieval, entity relationships, Neo4j RAG, graph database, connected data.

personAuthor: jakexiaohubgithub

GraphRAG Patterns

Combine knowledge graphs with RAG for complex reasoning over connected data.

When to Use GraphRAG vs Vector RAG

| Use Case | Vector RAG | GraphRAG | |----------|------------|----------| | Simple Q&A | ✅ | Overkill | | Factual lookup | ✅ | ✅ | | Multi-hop reasoning | ❌ | ✅ | | "How is X related to Y?" | ❌ | ✅ | | Entity relationships | ❌ | ✅ | | Compliance/audit trails | ❌ | ✅ | | Summarizing themes | ❌ | ✅ | | Explaining why items are connected | ❌ | ✅ (the path is the explanation) |

Core Architecture

┌─────────────────────────────────────────────────────────────┐
│                      User Query                              │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    Query Analyzer                            │
│         (Determine: vector, graph, or hybrid?)               │
└─────────────────────────────────────────────────────────────┘
                    │                    │
          ┌────────┴────────┐  ┌────────┴────────┐
          ▼                 ▼  ▼                 ▼
┌─────────────────┐  ┌─────────────────┐
│  Vector Search  │  │  Graph Traverse │
│  (Semantic)     │  │  (Structured)   │
└─────────────────┘  └─────────────────┘
          │                    │
          └────────┬──────────┘
                   ▼
┌─────────────────────────────────────────────────────────────┐
│                  Context Fusion                              │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    LLM Generation                            │
└─────────────────────────────────────────────────────────────┘

Pattern 1: Entity Extraction → Knowledge Graph

Model IDs: CHAT_MODEL in these examples is a placeholder. Set it to a current chat model ID from your provider's models page (for example CHAT_MODEL = os.environ["CHAT_MODEL"]); model IDs are retired over time.

import json
import re
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from neo4j import GraphDatabase

# Step 1: Extract entities and relationships from documents
EXTRACTION_PROMPT = """Extract entities and relationships from this text.

Text: {text}

Return JSON format:
{{
  "entities": [
    {{"name": "...", "type": "Person|Organization|Concept|Event|Location", "description": "..."}}
  ],
  "relationships": [
    {{"source": "...", "target": "...", "type": "WORKS_FOR|USES|PART_OF|RELATED_TO", "description": "..."}}
  ]
}}
"""

async def extract_knowledge(text: str, llm: ChatOpenAI) -> dict:
    """Extract entities and relationships from text."""
    prompt = ChatPromptTemplate.from_template(EXTRACTION_PROMPT)
    chain = prompt | llm
    result = await chain.ainvoke({"text": text})
    return json.loads(result.content)


# Step 2: Normalize entity names so "AWS" and "Amazon Web Services" become one node
ALIASES = {"aws": "Amazon Web Services", "amazon web services": "Amazon Web Services"}

def normalize(name: str) -> str:
    key = re.sub(r"\s+", " ", name).strip().lower()
    return ALIASES.get(key, name.strip())


# Step 3: Store in Neo4j
# Cypher cannot take labels or relationship types as parameters, so validate them
# against your schema before interpolating. Extracted text is untrusted input.
ENTITY_TYPES = {"Person", "Organization", "Concept", "Event", "Location"}
REL_TYPES = {"WORKS_FOR", "USES", "PART_OF", "RELATED_TO"}

class KnowledgeGraph:
    def __init__(self, uri: str, user: str, password: str):
        self.driver = GraphDatabase.driver(uri, auth=(user, password))

    def add_entity(self, name: str, entity_type: str, properties: dict | None = None):
        if entity_type not in ENTITY_TYPES:
            entity_type = "Concept"
        with self.driver.session() as session:
            session.run(
                f"MERGE (e:Entity:{entity_type} {{name: $name}}) SET e += $properties",
                name=normalize(name),
                properties=properties or {},
            )

    def add_relationship(self, source: str, target: str, rel_type: str, description: str = ""):
        if rel_type not in REL_TYPES:
            rel_type = "RELATED_TO"
        with self.driver.session() as session:
            session.run(
                f"""
                MATCH (a:Entity {{name: $source}})
                MATCH (b:Entity {{name: $target}})
                MERGE (a)-[r:{rel_type}]->(b)
                SET r.description = $description
                """,
                source=normalize(source),
                target=normalize(target),
                description=description,
            )

Use the same model and prompt for every document so entity types stay consistent, and keep the schema (ENTITY_TYPES, REL_TYPES) under version control: it will change as the corpus grows.

Pattern 2: Graph-Enhanced Retrieval

from llama_index.core import PropertyGraphIndex
from llama_index.graph_stores.neo4j import Neo4jPropertyGraphStore

def create_property_graph_index(documents):
    """Create a property graph index with LlamaIndex."""

    # Connect to Neo4j
    graph_store = Neo4jPropertyGraphStore(
        username="neo4j",
        password="password",
        url="bolt://localhost:7687",
    )

    # Build index - automatically extracts entities/relationships
    index = PropertyGraphIndex.from_documents(
        documents,
        property_graph_store=graph_store,
        show_progress=True,
    )

    return index


def query_with_graph(index, query: str):
    """Query using both vector and graph retrieval."""

    # Create retriever that uses both paths
    retriever = index.as_retriever(
        include_text=True,  # Include original text chunks
        similarity_top_k=5,
    )

    # Get results
    nodes = retriever.retrieve(query)
    return nodes

Pattern 3: Text-to-Cypher for Direct Graph Queries

from langchain_neo4j import GraphCypherQAChain, Neo4jGraph  # pip install langchain-neo4j

def create_text_to_cypher_chain():
    """Create a chain that converts natural language to Cypher queries."""

    # Connect to Neo4j
    graph = Neo4jGraph(
        url="bolt://localhost:7687",
        username="neo4j",
        password="password"
    )

    # Print schema for debugging
    print(graph.schema)

    # Create chain
    chain = GraphCypherQAChain.from_llm(
        llm=ChatOpenAI(model=CHAT_MODEL, temperature=0),
        graph=graph,
        verbose=True,
        validate_cypher=True,  # Validate before executing
        return_intermediate_steps=True,
        allow_dangerous_requests=True,  # required opt-in: use a read-only DB user
    )

    return chain


# Usage
chain = create_text_to_cypher_chain()
result = chain.invoke({
    "query": "What companies has John Smith worked for?"
})
# Generated Cypher: MATCH (p:Person {name: 'John Smith'})-[:WORKED_AT]->(c:Company) RETURN c.name

Pattern 4: Hybrid Vector + Graph Retrieval

class HybridGraphRAG:
    """Combine vector similarity with graph traversal."""

    def __init__(self, vector_store, graph_store):
        self.vector_store = vector_store
        self.graph_store = graph_store

    def retrieve(self, query: str, top_k: int = 5) -> list[dict]:
        # 1. Vector search for relevant chunks
        vector_results = self.vector_store.similarity_search(query, k=top_k)

        # 2. Extract entities from query
        query_entities = self._extract_entities(query)

        # 3. Graph traversal from those entities
        graph_context = []
        for entity in query_entities:
            # Get 1-hop neighbors. Pass the entity as a parameter, never via f-string.
            neighbors = self.graph_store.query(
                """
                MATCH (e:Entity {name: $name})-[r]-(n)
                RETURN e.name, type(r), n.name, n.description
                LIMIT 10
                """,
                params={"name": normalize(entity)},
            )
            graph_context.extend(neighbors)

        # 4. Combine results
        combined = {
            "vector_chunks": [r.page_content for r in vector_results],
            "graph_context": graph_context,
            "entities": query_entities
        }

        return combined

    def _extract_entities(self, text: str) -> list[str]:
        # Use NER or LLM to extract entities
        # Simplified version:
        prompt = f"Extract entity names from: {text}"
        # ... LLM call
        return entities

Variant: Expand From Entities in Retrieved Chunks

If chunks were tagged with the entities they mention at ingest time, start from the vector results instead of the query. This also works when the query names no entity:

def expand_from_chunks(vector_results: list, graph_store, max_entities: int = 5) -> list[str]:
    entities = []
    for doc in vector_results:
        for e in doc.metadata.get("entities", []):
            if e not in entities:
                entities.append(e)
    facts = []
    for entity in entities[:max_entities]:          # cap expansion to control prompt size
        rows = graph_store.query(
            "MATCH (e:Entity {name: $name})-[r]->(n) RETURN e.name AS s, type(r) AS rel, n.name AS o LIMIT 10",
            params={"name": entity},
        )
        facts.extend(f"{r['s']} -[{r['rel']}]-> {r['o']}" for r in rows)
    return facts

Pass these facts to the prompt under a separate "Entity relationships" heading so the model can tell them apart from text chunks.

Pattern 5: Path-Based Retrieval (Explain Connections)

For "How is X related to Y?", retrieve the path itself. The path is both the context and the explanation:

def explain_connection(driver, entity_a: str, entity_b: str) -> list[str]:
    # Variable-length bounds (the 4 in [*..4]) cannot be query parameters in Cypher;
    # keep them as validated literals.
    query = """
    MATCH (a:Entity {name: $a}), (b:Entity {name: $b})
    MATCH path = shortestPath((a)-[*..4]-(b))
    RETURN [n IN nodes(path) | n.name] AS names,
           [r IN relationships(path) | type(r)] AS rels
    """
    with driver.session() as session:
        record = session.run(query, a=normalize(entity_a), b=normalize(entity_b)).single()
    if record is None:
        return []  # no path: fall back to vector retrieval
    names, rels = record["names"], record["rels"]
    hops = [f"{names[i]} -[{rels[i]}]- {names[i + 1]}" for i in range(len(rels))]
    return hops

Keep hop limits small (2-4). Unbounded variable-length patterns can traverse much of the graph.

Pattern 6: Microsoft GraphRAG (Community Summaries)

Microsoft's GraphRAG extracts an entity graph, groups entities into a hierarchy of communities (Leiden clustering), and pre-writes a summary for each community. Global search answers corpus-wide questions ("What are the main themes?") from those summaries; local search answers entity-specific questions from the entity's neighborhood and source text.

It is driven by a CLI and a settings.yaml file rather than a Python API you call inline. As documented at the time of writing:

python -m pip install graphrag
mkdir -p ./ragtest/input && cp ./documents/*.txt ./ragtest/input/
cd ./ragtest
graphrag init            # writes settings.yaml and .env; set GRAPHRAG_API_KEY and models there
graphrag index           # builds the graph, communities, and summaries into ./output

graphrag query "What are the main themes in these documents?"            # global search (default)
graphrag query "What is Company X's main product?" --method local        # entity-focused

Indexing makes many LLM calls per document, so try it on a sample of the corpus and check the cost before indexing everything. Check the Get Started page for the current commands and options; the CLI has changed between releases.

When to Use Each Pattern

| Pattern | Use When | |---------|----------| | Entity Extraction → KG | Building from scratch, custom schema | | Property Graph Index | Quick setup, LlamaIndex ecosystem | | Text-to-Cypher | Existing graph, complex queries | | Hybrid Vector + Graph | Need both semantic + structural | | Path-Based Retrieval | "How is X related to Y?", explainable answers | | Microsoft GraphRAG | Large corpus, summarization queries |

Best Practices

  1. Define your schema - Know what entities and relationships matter, and version it
  2. Start simple - Begin with 2-3 entity types, expand as needed
  3. Extract consistently - Same model and prompt for every document
  4. Normalize entities - Merge aliases ("AWS" / "Amazon Web Services") into one node
  5. Validate Cypher - Validate generated queries, run them as a read-only database user, and never build Cypher from untrusted strings
  6. Limit depth - 2-3 hops is usually enough; cap expansion fan-out
  7. Cache graph queries - Graph traversals can be expensive
  8. Combine with vector - Pure graph misses semantic similarity
  9. Test multi-hop - Ensure 2-3 hop queries perform acceptably

Common Pitfalls

  • Over-extraction: Too many entities = noisy graph
  • Missing relationships: Entities without connections are useless
  • Schema drift: Inconsistent entity types break queries
  • Duplicate entities: Unnormalized aliases split one entity's facts across several nodes
  • Cypher injection: Entity names or relationship types from LLM output interpolated into queries
  • No fallback: Graph-only fails when entities not found

Tools & Resources

  • Neo4j: Production graph database
  • LlamaIndex PropertyGraphIndex: Easy Python integration
  • Microsoft GraphRAG: Community-based approach
  • Amazon Neptune: Managed graph database
  • LangChain GraphCypherQAChain: Text-to-Cypher chains

References

  • Microsoft GraphRAG docs: https://microsoft.github.io/graphrag/get_started/
  • From Local to Global: A Graph RAG Approach to Query-Focused Summarization (Edge et al., 2024): https://arxiv.org/abs/2404.16130
  • LlamaIndex PropertyGraphIndex with Neo4j: https://developers.llamaindex.ai/python/examples/property_graph/property_graph_neo4j/
  • LangChain Neo4j (langchain-neo4j, GraphCypherQAChain): https://python.langchain.com/docs/integrations/graphs/neo4j_cypher/
  • Cypher variable-length patterns: https://neo4j.com/docs/cypher-manual/current/patterns/variable-length-patterns/