Neo4j Python Driver
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
- breaking The way to access records and iterate through `Result` objects significantly changed when migrating from version 4.x to 5.x. Direct iteration over `Result` might behave differently or raise errors. Methods like `single()`, `data()`, and explicit iteration are now the standard.
- breaking The transaction API was revamped in 5.x. Functions like `session.read_transaction()` and `session.write_transaction()` now pass a `Transaction` object (`tx`) to the user-defined callback, rather than the `Session` object directly. Direct `session.run()` without an explicit transaction context often auto-commits.
- gotcha It is crucial to properly close `Driver` and `Session` objects to prevent connection leaks and ensure resource release. Drivers are designed to be long-lived, while sessions should be short-lived.
- gotcha Authentication token handling changed in 5.x. The `AuthTokens` module (e.g., `AuthTokens.basic`) is the recommended way to provide credentials, replacing simpler tuple-based authentication methods from older versions.
Install
-
pip install neo4j
Imports
- GraphDatabase
from neo4j import GraphDatabase
- AuthTokens
from neo4j import AuthTokens
Quickstart
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()