# How to Configure Neo4j as a Graph Database in Cognee

> Configure Neo4j as a graph database in Cognee by setting environment variables and `set_graph_db_config`. Learn how to use Neo4jAdapter for graph operations.

- Repository: [Topoteretes/cognee](https://github.com/topoteretes/cognee)
- Tags: how-to-guide
- Published: 2026-03-16

---

**You can configure Neo4j as Cognee's graph backend by setting environment variables for your Bolt connection and calling `cognee.config.set_graph_db_config()` with the provider set to "neo4j", which routes all graph operations through the `Neo4jAdapter` class.**

Cognee is an open-source knowledge graph platform (topoteretes/cognee) that stores data as property graphs. While it defaults to an in-memory NetworkX implementation, you can configure Neo4j as a graph database in Cognee to enable persistent, scalable graph storage and analytics.

## Prerequisites and Environment Setup

Before configuring Cognee, ensure you have a running Neo4j instance accessible via the Bolt protocol. You will need the connection URL, username, and password ready for the configuration step.

## Configuring the Neo4j Connection

Cognee supports two methods for passing credentials: environment variables or direct configuration in code.

### Environment Variables

Set these variables before starting your application:

- `GRAPH_DATABASE_URL` — The Bolt URL (e.g., `bolt://localhost:7687`)
- `GRAPH_DATABASE_USERNAME` — Your Neo4j username
- `GRAPH_DATABASE_PASSWORD` — Your Neo4j password

### Programmatic Configuration

Call `cognee.config.set_graph_db_config()` with a dictionary containing your credentials and the provider name:

```python
cognee.config.set_graph_db_config({
    "graph_database_url": "bolt://localhost:7687",
    "graph_database_provider": "neo4j",
    "graph_database_username": "neo4j",
    "graph_database_password": "your_password"
})

```

## How the Neo4jAdapter Works

The `Neo4jAdapter` class in [`cognee/infrastructure/databases/graph/neo4j_driver/adapter.py`](https://github.com/topoteretes/cognee/blob/main/cognee/infrastructure/databases/graph/neo4j_driver/adapter.py) implements the `GraphDBInterface` abstraction. It creates an asynchronous `AsyncGraphDatabase.driver` instance and exposes methods including `add_node`, `add_edge`, `query`, `extract_node`, and `get_neighbors`. All higher-level modules interact with this adapter through the common interface, requiring no code changes beyond configuration.

## Complete Configuration Example

Here is a runnable example that demonstrates the full workflow from configuration to search:

```python
import os
import cognee
from cognee.modules.search.types import SearchType

async def main():
    # Load credentials from environment

    neo4j_url  = os.getenv("GRAPH_DATABASE_URL")
    neo4j_user = os.getenv("GRAPH_DATABASE_USERNAME")
    neo4j_pass = os.getenv("GRAPH_DATABASE_PASSWORD")

    # Tell Cognee to use Neo4j

    cognee.config.set_graph_db_config({
        "graph_database_url":      neo4j_url,
        "graph_database_provider":"neo4j",
        "graph_database_username":neo4j_user,
        "graph_database_password":neo4j_pass,
    })

    # Example: add and process a document

    await cognee.add(["Neo4j is a graph DB"], "my_dataset")
    await cognee.cognify(["my_dataset"])

    # Graph-completion search (now runs against Neo4j)

    results = await cognee.search(
        query_type=SearchType.GRAPH_COMPLETION,
        query_text="graph database"
    )
    print(results)

# Run the coroutine

import asyncio
asyncio.run(main())

```

This example is available in the repository at [`examples/configurations/database_examples/neo4j_graph_database_configuration.py`](https://github.com/topoteretes/cognee/blob/main/examples/configurations/database_examples/neo4j_graph_database_configuration.py).

## Direct Adapter Usage (Advanced)

For custom implementations, instantiate `Neo4jAdapter` directly from `cognee.infrastructure.databases.graph.neo4j_driver.adapter`:

```python
from cognee.infrastructure.databases.graph.neo4j_driver.adapter import Neo4jAdapter

async def demo():
    adapter = Neo4jAdapter(
        graph_database_url="bolt://localhost:7687",
        graph_database_username="neo4j",
        graph_database_password="secret",
    )
    await adapter.initialize()          # creates uniqueness constraint

    await adapter.add_node(MyDataPoint(id="123", name="Alice"))
    await adapter.add_edge("123", "456", "KNOWS")
    neighbors = await adapter.get_neighbors("123")
    print(neighbors)

```

## Architecture and Data Flow

Understanding how Cognee routes graph operations helps debug configuration issues.

When you call `cognee.config.set_graph_db_config()`, Cognee stores the mapping in the global configuration object (managed in [`cognee/shared/configuration.py`](https://github.com/topoteretes/cognee/blob/main/cognee/shared/configuration.py)). The first time a graph operation is needed, `cognee.infrastructure.engine.get_graph_engine` reads the provider value. If it equals `"neo4j"`, it imports and instantiates `Neo4jAdapter` with the supplied credentials.

The adapter's `get_session` async context manager creates sessions bound to the optional database name (`graph_database_name`). Every query method opens a session via this manager, executes Cypher statements, and returns results as dictionaries.

Graph metrics are computed via helper functions in [`cognee/infrastructure/databases/graph/neo4j_driver/neo4j_metrics_utils.py`](https://github.com/topoteretes/cognee/blob/main/cognee/infrastructure/databases/graph/neo4j_driver/neo4j_metrics_utils.py), which call the adapter to calculate clustering coefficients, edge density, and connected components.

## Summary

- Set `GRAPH_DATABASE_URL`, `GRAPH_DATABASE_USERNAME`, and `GRAPH_DATABASE_PASSWORD` environment variables or pass them directly to `cognee.config.set_graph_db_config()`.
- Specify `"neo4j"` as the `graph_database_provider` to route operations to the Neo4j backend.
- The `Neo4jAdapter` in [`cognee/infrastructure/databases/graph/neo4j_driver/adapter.py`](https://github.com/topoteretes/cognee/blob/main/cognee/infrastructure/databases/graph/neo4j_driver/adapter.py) handles all CRUD operations asynchronously through the `GraphDBInterface` abstraction.
- All high-level API methods (`cognee.add`, `cognee.cognify`, `cognee.search`) automatically use Neo4j once configured.
- Graph metrics and analytics utilize [`neo4j_metrics_utils.py`](https://github.com/topoteretes/cognee/blob/main/neo4j_metrics_utils.py) for statistical calculations.

## Frequently Asked Questions

### What environment variables are required to configure Neo4j in Cognee?

You must set `GRAPH_DATABASE_URL` (the Bolt connection string), `GRAPH_DATABASE_USERNAME`, and `GRAPH_DATABASE_PASSWORD`. Optionally, you can specify `GRAPH_DATABASE_NAME` to target a specific database within your Neo4j instance.

### How does Cognee switch between NetworkX and Neo4j?

Cognee uses `cognee.infrastructure.engine.get_graph_engine` to lazily instantiate the appropriate adapter based on the `graph_database_provider` value stored in the global configuration. When set to `"neo4j"`, it loads the `Neo4jAdapter`; otherwise, it defaults to the in-memory NetworkX implementation.

### Can I use the Neo4jAdapter directly without the high-level API?

Yes. You can import `Neo4jAdapter` from `cognee.infrastructure.databases.graph.neo4j_driver.adapter` and instantiate it directly with your credentials. This is useful for custom ETL pipelines or when you need fine-grained control over graph transactions outside of the standard `cognee.add` workflow.

### Where are graph metrics calculated in the Neo4j implementation?

Graph-level statistics such as clustering coefficients, edge density, and connected components are calculated in [`cognee/infrastructure/databases/graph/neo4j_driver/neo4j_metrics_utils.py`](https://github.com/topoteretes/cognee/blob/main/cognee/infrastructure/databases/graph/neo4j_driver/neo4j_metrics_utils.py). These utilities call the `Neo4jAdapter` to execute Cypher queries and return metric data used by the descriptive metrics test suite and graph analytics tasks.