Building a Deep Graph RAG System with Neo4j and Python: Beyond Vector Search

AI tutorial - IT technology blog
AI tutorial - IT technology blog

The Breaking Point: When Vector Search Failed Our Production RAG Pipeline

Six months ago, our team shipped an internal incident response assistant for an engineering org running 140 microservices. The stack was standard fare: LangChain, a managed vector database, and cosine similarity over 1,200 chunked confluence runbooks and API specs. On paper, recall reached 89% on our synthetic eval set. In production, platform engineers tore it apart within 48 hours.

An on-call engineer asked: “Which security patches released last quarter apply to microservices dependent on Service B?”

The vector search sputtered. It returned generic chunks detailing Q3 CVE announcements, the top-level README for Service B, and unrelated deployment manifests. The LLM then stitched together an authoritative, completely bogus answer. It hallucinated dependency chains that did not exist. Fixed 500-token chunking had cleanly severed the parent-child relationships, leaving the model blind to how the services actually talk to each other.

Root Cause Analysis: Why Dense Vectors Fall Short in Complex Reasoning

Vector search excels at semantic proximity—matching “authentication timeout” to “login gateway latency.” But complex system queries demand topology, not just semantic similarity. Dense retrieval breaks down across three distinct failure modes:

  • Multi-hop Blindness: Vectors evaluate snippets in isolation. They cannot follow transitive paths like Service A → Service B → DB Cluster C without manual query chaining.
  • Aggregation Failure: Global audits expose severe recall cliffs. Asking “Which services expose unauthenticated metrics endpoints?” retrieves the top 10 most similar paragraphs, leaving dozens of affected components undiscovered.
  • Chunk Boundary Fragmentation: Arbitrary token splits cut directly through tables, dependency trees, and configuration blocks. Rerankers then score half an entity reference and discard the rest.

Evaluating the Alternatives: Fine-Tuning vs. 1M+ Context Windows vs. Graph RAG

Before overhauling our retrieval layer, we benchmarked three potential solutions across cost, latency, and operational overhead:

1. Domain Fine-Tuning

Weight updates bake domain terminology into the model, but our topologies shift with weekly CI/CD deploys. Retraining costs roughly $800 to $2,500 per run on specialized corpora, provides zero deterministic provenance, and still fails on multi-hop graph traversals under pressure.

2. Million-Token Context Windows

Stuffing complete service directories into 1M-token windows works for periodic batch jobs. In live incident triage, however, time-to-first-token (TTFT) routinely spiked past 9 seconds. At 400 queries a day, raw token billing made this path completely unsustainable.

3. Graph-Augmented RAG (The Winner)

Graph RAG bridges unstructured semantic search and deterministic relationship engines. Storing entities in Neo4j with vector properties gives us the best of both worlds: vector search discovers the entry node, while Cypher traverses interconnected dependencies deterministically.

The Architecture: Knowledge Graphs, Cypher, and Vector Search

Moving from naive chunking to graph retrieval requires a clear separation of concerns across your database layer. The production pipeline hinges on three components inside Neo4j:

  1. Entity & Relation Extraction: Deconstruct raw operational text into discrete nodes (Service, Patch, Database) and typed edges (DEPENDS_ON, RUNS_VERSION, EXPOSES).
  2. Native Vector Indexing: Store embeddings directly on node properties inside Neo4j 5.x+, avoiding synchronization drift between separate vector stores and graph tables.
  3. Hybrid Cypher Retrieval: Pinpoint the entry node via approximate nearest neighbors (ANN), then execute 1- to 3-hop graph walks to pull the surrounding dependency graph into context.

Step-by-Step Implementation in Python

1. Setting Up the Neo4j Environment

Spin up Neo4j 5.20 with the APOC utility library using Docker:

docker run -d \
  --name neo4j-graphrag \
  -p 7474:7474 -p 7687:7687 \
  -e NEO4J_AUTH=neo4j/StrongPassword123 \
  -e NEO4J_PLUGINS='["apoc"]' \
  neo4j:5.20.0

2. Connecting and Defining Schema

Install the official Python driver and the OpenAI client library:

pip install neo4j openai

Initialize the driver and create a native vector index on Service entity nodes:

from neo4j import GraphDatabase

URI = "bolt://localhost:7687"
AUTH = ("neo4j", "StrongPassword123")

driver = GraphDatabase.driver(URI, auth=AUTH)

def initialize_schema(tx):
    # Index node embeddings with 1536 dimensions for text-embedding-3-small
    tx.run("""
    CREATE VECTOR INDEX service_vector_index IF NOT EXISTS
    FOR (s:Service) ON (s.embedding)
    OPTIONS {indexConfig: {
      `vector.dimensions`: 1536,
      `vector.similarity_function`: 'cosine'
    }}
    """)

with driver.session() as session:
    session.execute_write(initialize_schema)
    print("Schema and vector index initialized.")

3. Ingesting Structured Knowledge

Populate the graph with interconnected microservices, directional dependencies, and node embeddings:

from openai import OpenAI

client = OpenAI(api_key="your-openai-key")

def get_embedding(text: str) -> list[float]:
    response = client.embeddings.create(
        input=text,
        model="text-embedding-3-small"
    )
    return response.data[0].embedding

def seed_database(tx):
    services = [
        ("AuthService", "Handles user authentication and JWT validation tokens."),
        ("BillingService", "Processes subscriptions and communicates with Stripe."),
        ("PaymentGateway", "Core transaction router; directly depends on AuthService for identity verification.")
    ]
    
    for name, desc in services:
        emb = get_embedding(desc)
        tx.run("""
        MERGE (s:Service {name: $name})
        SET s.description = $desc, s.embedding = $emb
        """, name=name, desc=desc, emb=emb)
    
    # Establish dependency topology
    tx.run("""
    MATCH (p:Service {name: 'PaymentGateway'}), (a:Service {name: 'AuthService'})
    MERGE (p)-[:DEPENDS_ON {protocol: 'gRPC', timeout_ms: 250}]->(a)
    """)
    
    tx.run("""
    MATCH (b:Service {name: 'BillingService'}), (p:Service {name: 'PaymentGateway'})
    MERGE (b)-[:DEPENDS_ON {protocol: 'REST', timeout_ms: 1000}]->(p)
    """)

with driver.session() as session:
    session.execute_write(seed_database)
    print("Graph topology and embeddings populated.")

4. Performing Hybrid Retrieval (Vector + Graph Traversal)

When an incident report comes in, ANN search identifies the likely fault area. From there, Cypher takes over to trace upstream paths up to two hops away:

def hybrid_graph_retrieval(query_text: str, top_k: int = 1):
    query_vector = get_embedding(query_text)
    
    cypher_query = """
    CALL db.index.vector.queryNodes('service_vector_index', $top_k, $query_vector)
    YIELD node AS matched_service, score
    OPTIONAL MATCH path = (matched_service)-[:DEPENDS_ON*1..2]->(upstream:Service)
    RETURN 
        matched_service.name AS service,
        matched_service.description AS description,
        score,
        [node IN nodes(path) | node.name] AS dependency_chain
    """
    
    results = []
    with driver.session() as session:
        records = session.run(cypher_query, top_k=top_k, query_vector=query_vector)
        for record in records:
            results.append({
                "service": record["service"],
                "description": record["description"],
                "score": record["score"],
                "dependency_chain": record["dependency_chain"]
            })
    return results

query = "We are seeing payment transaction failures and checkout timeouts."
context = hybrid_graph_retrieval(query)
print(context)

5. Synthesizing Grounded Answers with the LLM

Supply the recovered graph paths directly into the prompt. The LLM now reasons over deterministic structural traces rather than guessing service links:

def generate_answer(user_prompt: str, context: list) -> str:
    # Flatten paths while dropping redundant nodes
    unique_paths = []
    for c in context:
        chain = c.get('dependency_chain')
        if chain:
            formatted = " -> ".join(chain)
            if formatted not in unique_paths:
                unique_paths.append(formatted)
                
    formatted_context = "\n".join([
        f"- Matched Entrypoint: {c['service']} (Similarity: {c['score']:.3f})\n  Summary: {c['description']}"
        for c in context
    ])
    
    paths_context = "\n".join([f"- {p}" for p in unique_paths]) if unique_paths else "None detected"
    
    prompt = f"""System Architecture Context:
{formatted_context}

Discovered Upstream Dependency Chains:
{paths_context}

Incident Details: {user_prompt}
Identify the most likely cascading failure points and trace the root dependencies."""

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": prompt}],
        temperature=0
    )
    return response.choices[0].message.content

final_output = generate_answer(query, context)
print("\n--- Root Cause Summary ---\n", final_output)

Observations After Six Months in Production

Replacing pure vector similarity with hybrid graph retrieval transformed our incident triage workflow:

  • Hallucinations plummeted: Hallucinated architectural dependencies dropped from 31.4% on naive RAG to under 4% across 800+ audited queries.
  • Deterministic Debugging: Every suggestion includes an auditable Cypher graph walk. Engineers inspect the exact traversal path instead of parsing arbitrary cosine scores.
  • Sub-Millisecond Schema Updates: When engineers deploy changes, an event listener writes a single relationship edge to Neo4j. Zero vector recalculations or document re-indexing required.
  • Predictable Latency: Retrieval and traversal average 28ms locally and 62ms over VPC networks, well within real-time SLA thresholds.

If your documentation covers layered microservices, compliance frameworks, or recursive data models, pure vector search will hit a ceiling. Knowledge graphs provide the rigid relational rails that modern LLMs need to deliver trustworthy production answers.

Share: