> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/getzep/graphiti/llms.txt
> Use this file to discover all available pages before exploring further.

# Neo4jDriver

> Neo4j graph database driver implementation

The `Neo4jDriver` class provides connectivity to Neo4j graph databases with full ACID transaction support.

## Overview

Neo4j is the industry-standard graph database platform. The Neo4jDriver leverages the official `neo4j` Python driver to provide:

* Full ACID transaction support
* Automatic index and constraint creation
* Connection pooling
* Concurrent query execution
* Health checks

## Constructor

```python theme={null}
from graphiti_core.driver.neo4j_driver import Neo4jDriver

driver = Neo4jDriver(
    uri="bolt://localhost:7687",
    user="neo4j",
    password="password",
    database="neo4j"
)
```

### Parameters

<ParamField path="uri" type="str" required>
  The connection URI for the Neo4j database.

  Supported URI schemes:

  * `bolt://` - Unencrypted connection
  * `bolt+s://` - Encrypted connection with full certificate
  * `bolt+ssc://` - Encrypted connection, self-signed certificate
  * `neo4j://` - Routing driver (for clusters)
  * `neo4j+s://` - Encrypted routing driver

  Example: `"bolt://localhost:7687"`
</ParamField>

<ParamField path="user" type="str | None" required>
  The username for Neo4j authentication.

  Can be `None` for databases without authentication (not recommended for production).

  Example: `"neo4j"`
</ParamField>

<ParamField path="password" type="str | None" required>
  The password for Neo4j authentication.

  Can be `None` for databases without authentication (not recommended for production).

  Example: `"password"`
</ParamField>

<ParamField path="database" type="str" default="neo4j">
  The name of the Neo4j database to connect to.

  Neo4j supports multiple databases. The default database is typically named `"neo4j"`.

  Example: `"graphiti"`
</ParamField>

## Methods

### execute\_query

Execute a Cypher query and return results.

```python theme={null}
result = await driver.execute_query(
    "MATCH (n:Entity) RETURN n LIMIT 10",
    params={"limit": 10}
)
```

**Parameters:**

* `cypher_query_` (str) - The Cypher query to execute
* `**kwargs` - Query parameters

**Returns:** `EagerResult` - Neo4j result object

### session

Create a new database session.

```python theme={null}
session = driver.session(database="neo4j")
try:
    result = await session.run("MATCH (n) RETURN count(n)")
finally:
    await session.close()
```

**Parameters:**

* `database` (str | None) - Optional database name override

**Returns:** `GraphDriverSession` - Session object

### transaction

Context manager for ACID transactions.

```python theme={null}
async with driver.transaction() as tx:
    await tx.run("CREATE (n:Entity {uuid: $uuid})", uuid="123")
    await tx.run("CREATE (m:Entity {uuid: $uuid})", uuid="456")
    # Automatically commits on success, rolls back on exception
```

**Returns:** `AsyncIterator[Transaction]` - Transaction context manager

### close

Close the driver and release all connections.

```python theme={null}
await driver.close()
```

**Returns:** `None`

### build\_indices\_and\_constraints

Create all required indices and constraints for Graphiti.

```python theme={null}
await driver.build_indices_and_constraints(delete_existing=False)
```

**Parameters:**

* `delete_existing` (bool) - If True, delete existing indices before creating new ones

**Returns:** `None`

<Note>
  This method is automatically called during driver initialization. You typically don't need to call it manually unless you want to rebuild indices.
</Note>

### health\_check

Verify connectivity to the Neo4j database.

```python theme={null}
try:
    await driver.health_check()
    print("Connection healthy")
except Exception as e:
    print(f"Connection failed: {e}")
```

**Returns:** `None` - Raises exception if connection fails

### with\_database

Create a shallow copy of the driver targeting a different database.

```python theme={null}
default_driver = Neo4jDriver(
    uri="bolt://localhost:7687",
    user="neo4j",
    password="password",
    database="neo4j"
)

# Create a driver for a different database
other_driver = default_driver.with_database("other_db")
```

**Parameters:**

* `database` (str) - The name of the database to target

**Returns:** `GraphDriver` - New driver instance with different database

## Properties

### provider

```python theme={null}
driver.provider  # GraphProvider.NEO4J
```

Returns the `GraphProvider.NEO4J` enum value.

### Operations Properties

The driver exposes specialized operation interfaces:

```python theme={null}
driver.entity_node_ops       # EntityNodeOperations
driver.episode_node_ops      # EpisodeNodeOperations
driver.community_node_ops    # CommunityNodeOperations
driver.saga_node_ops         # SagaNodeOperations
driver.entity_edge_ops       # EntityEdgeOperations
driver.episodic_edge_ops     # EpisodicEdgeOperations
driver.community_edge_ops    # CommunityEdgeOperations
driver.has_episode_edge_ops  # HasEpisodeEdgeOperations
driver.next_episode_edge_ops # NextEpisodeEdgeOperations
driver.search_ops            # SearchOperations
driver.graph_ops             # GraphMaintenanceOperations
```

These properties provide access to database-specific implementations of graph operations.

## Usage Examples

### Basic Connection

```python theme={null}
import asyncio
from graphiti_core.driver.neo4j_driver import Neo4jDriver

async def main():
    driver = Neo4jDriver(
        uri="bolt://localhost:7687",
        user="neo4j",
        password="password"
    )
    
    try:
        # Verify connection
        await driver.health_check()
        print("Connected to Neo4j")
        
        # Execute a query
        result = await driver.execute_query(
            "MATCH (n:Entity) RETURN count(n) as count"
        )
        print(f"Entity count: {result.records[0]['count']}")
    finally:
        await driver.close()

asyncio.run(main())
```

### With Graphiti

```python theme={null}
import os
from graphiti_core import Graphiti
from graphiti_core.driver.neo4j_driver import Neo4jDriver

# Create driver
driver = Neo4jDriver(
    uri=os.environ.get("NEO4J_URI", "bolt://localhost:7687"),
    user=os.environ.get("NEO4J_USER", "neo4j"),
    password=os.environ.get("NEO4J_PASSWORD", "password")
)

# Initialize Graphiti
graphiti = Graphiti(graph_driver=driver)

# Or use shorthand for Neo4j
graphiti = Graphiti(
    uri="bolt://localhost:7687",
    user="neo4j",
    password="password"
)
```

### Using Transactions

```python theme={null}
from graphiti_core.driver.neo4j_driver import Neo4jDriver

driver = Neo4jDriver(
    uri="bolt://localhost:7687",
    user="neo4j",
    password="password"
)

try:
    async with driver.transaction() as tx:
        # All operations in this block are part of the same transaction
        await tx.run(
            "CREATE (e:Entity {uuid: $uuid, name: $name})",
            uuid="entity-1",
            name="Example Entity"
        )
        await tx.run(
            "CREATE (e:Entity {uuid: $uuid, name: $name})",
            uuid="entity-2",
            name="Another Entity"
        )
        # Transaction commits automatically on success
        # Rolls back automatically on exception
except Exception as e:
    print(f"Transaction failed: {e}")
finally:
    await driver.close()
```

### Azure OpenAI Integration

```python theme={null}
import os
from openai import AsyncOpenAI
from graphiti_core import Graphiti
from graphiti_core.driver.neo4j_driver import Neo4jDriver
from graphiti_core.llm_client.azure_openai_client import AzureOpenAILLMClient
from graphiti_core.embedder.azure_openai import AzureOpenAIEmbedderClient
from graphiti_core.llm_client.config import LLMConfig

# Azure OpenAI setup
azure_client = AsyncOpenAI(
    base_url=f"{os.environ['AZURE_OPENAI_ENDPOINT']}/openai/v1/",
    api_key=os.environ['AZURE_OPENAI_API_KEY']
)

llm_client = AzureOpenAILLMClient(
    azure_client=azure_client,
    config=LLMConfig(
        model="gpt-4.1",
        small_model="gpt-4.1"
    )
)

embedder_client = AzureOpenAIEmbedderClient(
    azure_client=azure_client,
    model="text-embedding-3-small"
)

# Initialize with Neo4j and Azure OpenAI
graphiti = Graphiti(
    uri="bolt://localhost:7687",
    user="neo4j",
    password="password",
    llm_client=llm_client,
    embedder=embedder_client
)
```

## Environment Variables

Common environment variables for Neo4j configuration:

```bash theme={null}
NEO4J_URI=bolt://localhost:7687
NEO4J_USER=neo4j
NEO4J_PASSWORD=password
NEO4J_DATABASE=neo4j
```

Load in your application:

```python theme={null}
import os
from dotenv import load_dotenv
from graphiti_core.driver.neo4j_driver import Neo4jDriver

load_dotenv()

driver = Neo4jDriver(
    uri=os.environ.get("NEO4J_URI", "bolt://localhost:7687"),
    user=os.environ.get("NEO4J_USER", "neo4j"),
    password=os.environ.get("NEO4J_PASSWORD", "password"),
    database=os.environ.get("NEO4J_DATABASE", "neo4j")
)
```

## Thread Safety

The Neo4jDriver is thread-safe and uses connection pooling. You can safely:

* Share a single driver instance across multiple coroutines
* Execute concurrent queries
* Create multiple sessions from the same driver

```python theme={null}
import asyncio

driver = Neo4jDriver(
    uri="bolt://localhost:7687",
    user="neo4j",
    password="password"
)

# Execute queries concurrently
results = await asyncio.gather(
    driver.execute_query("MATCH (n:Entity) RETURN count(n)"),
    driver.execute_query("MATCH (e:Episode) RETURN count(e)"),
    driver.execute_query("MATCH (c:Community) RETURN count(c)")
)
```

## Related

<CardGroup cols={2}>
  <Card title="Drivers Overview" icon="database" href="/api/drivers/overview">
    Learn about the driver architecture
  </Card>

  <Card title="Graphiti" icon="chart-network" href="/api/graphiti">
    Main Graphiti class documentation
  </Card>

  <Card title="FalkorDB Driver" icon="bolt" href="/api/drivers/falkordb">
    Alternative Redis-based driver
  </Card>

  <Card title="Kuzu Driver" icon="rocket" href="/api/drivers/kuzu">
    Embedded analytics driver
  </Card>
</CardGroup>
