Neo4j Python Driver

6.1.0 · active · verified Thu Apr 09

The Neo4j Python Driver is the official client library for interacting with Neo4j graph databases from Python applications. It uses the Bolt protocol for efficient communication. The library maintains multiple major versions, including LTS releases, and typically sees minor and patch updates every few weeks, with new major versions released periodically to introduce significant features or breaking changes. The current stable version is 6.1.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a Neo4j database using environment variables, create and manage a driver, use `AuthTokens` for authentication, and execute Cypher queries within read/write transactions. It showcases creating and finding nodes, emphasizing proper session and driver resource management.

import os
from neo4j import GraphDatabase, AuthTokens

# Configure connection details using environment variables
NEO4J_URI = os.environ.get("NEO4J_URI", "bolt://localhost:7687")
NEO4J_USERNAME = os.environ.get("NEO4J_USERNAME", "neo4j")
NEO4J_PASSWORD = os.environ.get("NEO4J_PASSWORD", "password") # Use a strong password in production

class Neo4jApp:
    def __init__(self, uri, username, password):
        self.driver = GraphDatabase.driver(uri, auth=AuthTokens.basic(username, password))

    def close(self):
        self.driver.close()

    def create_person(self, name):
        with self.driver.session() as session:
            greeting = session.execute_write(self._create_and_return_person, name)
            print(f"Created person: {greeting}")

    @staticmethod
    def _create_and_return_person(tx, name):
        query = (
            "CREATE (p:Person {name: $name}) "
            "RETURN p.name AS name"
        )
        result = tx.run(query, name=name)
        return result.single()["name"]

    def find_person(self, name):
        with self.driver.session() as session:
            person_name = session.execute_read(self._find_and_return_person, name)
            print(f"Found person: {person_name}")

    @staticmethod
    def _find_and_return_person(tx, name):
        query = (
            "MATCH (p:Person {name: $name}) "
            "RETURN p.name AS name"
        )
        result = tx.run(query, name=name)
        record = result.single()
        return record["name"] if record else None

if __name__ == "__main__":
    # Example usage (ensure Neo4j is running and accessible)
    # To run this, you'd typically set NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD
    # in your environment or update the defaults.
    app = Neo4jApp(NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD)
    try:
        app.create_person("Alice")
        app.find_person("Alice")
        app.create_person("Bob")
        app.find_person("Bob")
    finally:
        app.close()

view raw JSON →