How to Configure LightRAG with Neo4j for Production Knowledge Graph Storage

LightRAG provides a production-ready Neo4j backend via Neo4JStorage that automatically handles connection pooling, workspace isolation, B-tree indexing, and full-text search with automatic retries on transient errors.

The HKUDS/LightRAG repository ships with a native Neo4j storage implementation (Neo4JStorage) that persists knowledge graphs to Neo4j instead of memory. When you configure LightRAG with Neo4j, the storage layer manages schema creation, connection resilience, and multi-tenant isolation through environment variables or configuration files. This guide walks through deploying Neo4j, initializing the storage layer, and executing CRUD operations using the actual source implementation found in lightrag/kg/neo4j_impl.py.

Deploy a Neo4j Instance

LightRAG supports any Neo4j 5.x deployment. Choose the topology that matches your operational requirements:

  • Docker (Community or Enterprise). Run locally for development or mount persistent volumes for single-node production:
docker run -d --name neo4j \
  -p7474:7474 -p7687:7687 \
  -e NEO4J_AUTH=neo4j/securepassword \
  -v /data/neo4j:/data \
  neo4j:5
  • Neo4j Aura. Use the managed SaaS offering for automatic backups and TLS. Obtain the Bolt URI, username, and password from the Aura console, then set NEO4J_URI=neo4j+s://your-id.databases.neo4j.io.

  • Self-hosted Enterprise. Install via official packages or Helm charts. Enable mandatory TLS with dbms.connector.bolt.tls_level=REQUIRED and configure NEO4J_DATABASE for multi-database isolation.

Install the Neo4j Driver

LightRAG installs the official neo4j Python driver automatically via pipmaster when the storage class is first instantiated. The import is guarded in lightrag/kg/neo4j_impl.py (lines 22-30), meaning you do not need to manually add the package to your requirements. The driver becomes available immediately upon calling Neo4JStorage.

Configure Environment Variables

The Neo4JStorage class reads configuration from environment variables using dotenv (lines 34-38 in lightrag/kg/neo4j_impl.py). Create a .env file in your project root with the following variables:

Variable Example Purpose
NEO4J_URI bolt://localhost:7687 Bolt protocol endpoint.
NEO4J_USERNAME neo4j Authentication user.
NEO4J_PASSWORD securepassword Authentication password.
NEO4J_WORKSPACE production Logical workspace label for multi-tenant isolation.
NEO4J_MAX_CONNECTION_POOL_SIZE 200 Driver connection pool for concurrent workloads.
NEO4J_DATABASE knowledgegraph Target database name (Enterprise only).
NEO4J_MAX_TRANSACTION_RETRY_TIME 30 Seconds to retry transient failures.

Sample .env configuration:

NEO4J_URI=bolt://localhost:7687
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD=verysecret
NEO4J_WORKSPACE=production
NEO4J_MAX_CONNECTION_POOL_SIZE=200
NEO4J_KEEP_ALIVE=true

Initialize Neo4JStorage

Instantiate the storage class with a namespace and embedding function, then call initialize() to provision indexes and verify connectivity:

from lightrag.kg.neo4j_impl import Neo4JStorage

kg_storage = Neo4JStorage(
    namespace="myapp",
    global_config={"max_graph_nodes": 2000},
    embedding_func=my_embedder,
)

await kg_storage.initialize()

The initialize() method performs three critical setup tasks defined in lightrag/kg/neo4j_impl.py:

  1. Workspace Labeling. Sanitizes the NEO4J_WORKSPACE value (or defaults to base) to create an isolated label namespace (lines 93-106).
  2. B-Tree Index. Creates a B-tree index on entity_id for O(log n) lookups (lines 66-73).
  3. Full-Text Index. Provisions a full-text index named entity_id_fulltext_idx_<workspace> with CJK analyzer support when available (lines 87-115).

If index creation fails (for example, on unsupported Neo4j editions), LightRAG logs a warning and falls back to unindexed queries rather than crashing.

Upsert Nodes and Edges

Upsert a Node

Use upsert_node to merge entities into the graph. The method sanitizes entity_type and applies the workspace label automatically (lines 30-55):

await kg_storage.upsert_node(
    node_id="doc:12345",
    node_data={
        "entity_id": "doc:12345",
        "entity_type": "Document",
        "title": "Production Configuration Guide",
        "text": "Full article text...",
        "embedding": await my_embedder("Full article text...")
    },
)

Upsert an Edge

The upsert_edge method creates a directed relationship between two nodes, ensuring both endpoints exist before writing (lines 100-120):

await kg_storage.upsert_edge(
    source_node_id="doc:12345",
    target_node_id="topic:Neo4j",
    edge_data={"weight": 1.0, "description": "covers"}
)

Both operations are wrapped in tenacity retry decorators that handle transient Neo4j errors such as ServiceUnavailable and connection resets (lines 56-62, 119-133).

Query the Knowledge Graph

LightRAG exposes async read methods optimized for production use:

  • has_node(node_id). Returns True if the entity exists, utilizing the B-tree index for constant-time existence checks.
  • get_node(node_id). Retrieves node properties with workspace labels stripped for clean application logic.
  • get_knowledge_graph(node_label, max_depth, max_nodes). Returns a subgraph structure suitable for LLM reasoning, automatically truncating results when limits are exceeded.

All read methods use the @READ_RETRY decorator to mitigate transient read failures.

Production Optimization

Enable these configurations for high-availability deployments:

  1. Enable TLS. Set dbms.connector.bolt.tls_level=REQUIRED in Neo4j and use NEO4J_URI=neo4j+s://host:7687 for encrypted connections.
  2. Tune Connection Pools. Set NEO4J_MAX_CONNECTION_POOL_SIZE to match your application's concurrent request volume (default is typically 100).
  3. Use Enterprise Database Isolation. Set NEO4J_DATABASE to a dedicated database name for resource quotas and backup isolation.
  4. Monitor Index Health. Check logs during initialization for warnings about unsupported index operations. Re-run initialize() after upgrading Neo4j versions to migrate indexes.

Summary

  • Environment variables drive all Neo4j connectivity; place them in .env or export directly.
  • Neo4JStorage.initialize() provisions B-tree and full-text indexes automatically and establishes the workspace label for multi-tenancy.
  • upsert_node and upsert_edge handle entity sanitization and relationship creation with automatic retry logic on transient failures.
  • Workspace labels (controlled via NEO4J_WORKSPACE) allow multiple LightRAG instances to share a single Neo4j cluster safely.
  • Retry decorators on all I/O operations ensure resilience against network instability or brief Neo4j unavailability.

Frequently Asked Questions

Does LightRAG support Neo4j Aura?

Yes. Configure NEO4J_URI with the neo4j+s:// scheme provided by Aura, set NEO4J_USERNAME and NEO4J_PASSWORD to your Aura credentials, and omit NEO4J_DATABASE unless using an Enterprise Aura instance. The driver automatically handles TLS certificate verification.

How does LightRAG handle transient connection failures?

All CRUD operations in lightrag/kg/neo4j_impl.py are decorated with tenacity retry policies (lines 56-62 and 119-133) that catch ServiceUnavailable, TransientError, and connection resets. The driver retries with exponential backoff up to the limit specified in NEO4J_MAX_TRANSACTION_RETRY_TIME (default 30 seconds).

Can multiple LightRAG applications share one Neo4j database?

Yes. Set a unique NEO4J_WORKSPACE value for each application. The storage layer prepends this workspace string to all node labels (lines 93-106), effectively isolating graphs within the same physical database. For stricter isolation, use Neo4j Enterprise and specify different NEO4J_DATABASE values.

What indexes does LightRAG create automatically?

During initialization, LightRAG attempts to create two indexes: a B-tree index on the entity_id property for exact lookups (lines 66-73) and a full-text index named entity_id_fulltext_idx_<workspace> with CJK analyzer support for semantic search (lines 87-115). If the Neo4j edition lacks index administration privileges, LightRAG logs a warning and continues operation without indexes.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →