Neo4j Bolt driver for Python providing database connectivity and query execution
npx @tessl/cli install tessl/pypi-neo4j@5.28.00
# Neo4j Python Driver
1
2
The Neo4j Python driver provides connectivity to Neo4j graph databases using the efficient Bolt protocol. It supports both synchronous and asynchronous programming models, offering comprehensive database operations including transactions, sessions, and advanced features like query routing, connection pooling, and causal consistency through bookmarks.
3
4
## Package Information
5
6
- **Package Name**: neo4j
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install neo4j`
10
- **Requires Python**: >=3.7
11
12
## Core Imports
13
14
```python
15
import neo4j
16
```
17
18
Most commonly used imports:
19
20
```python
21
from neo4j import GraphDatabase, Driver, Session, Result
22
from neo4j import basic_auth, Auth
23
from neo4j import Record, Query, Bookmark
24
```
25
26
For graph and temporal data types:
27
28
```python
29
from neo4j.graph import Node, Relationship, Path
30
from neo4j.time import Date, DateTime, Time, Duration
31
from neo4j.spatial import Point, CartesianPoint, WGS84Point
32
```
33
34
For exception handling:
35
36
```python
37
from neo4j.exceptions import (
38
Neo4jError, ClientError, TransientError, DriverError,
39
ServiceUnavailable, AuthError, CypherSyntaxError,
40
ResultNotSingleError, SessionExpired
41
)
42
```
43
44
For async operations:
45
46
```python
47
from neo4j import AsyncGraphDatabase, AsyncDriver, AsyncSession, AsyncResult
48
from neo4j import AsyncManagedTransaction, AsyncTransaction
49
```
50
51
## Basic Usage
52
53
```python
54
from neo4j import GraphDatabase, basic_auth
55
56
# Create a driver instance
57
driver = GraphDatabase.driver(
58
"bolt://localhost:7687",
59
auth=basic_auth("neo4j", "password")
60
)
61
62
# Execute a simple query using execute_query (recommended)
63
records, summary, keys = driver.execute_query(
64
"CREATE (n:Person {name: $name}) RETURN n",
65
name="Alice"
66
)
67
68
# Alternative: Use session for more complex operations
69
with driver.session() as session:
70
result = session.run("MATCH (n:Person) RETURN n.name AS name")
71
for record in result:
72
print(record["name"])
73
74
# Always close the driver when done
75
driver.close()
76
```
77
78
Async usage:
79
80
```python
81
import asyncio
82
from neo4j import AsyncGraphDatabase, basic_auth
83
84
async def main():
85
driver = AsyncGraphDatabase.driver(
86
"bolt://localhost:7687",
87
auth=basic_auth("neo4j", "password")
88
)
89
90
# Execute query asynchronously
91
records, summary, keys = await driver.execute_query(
92
"MATCH (n:Person) RETURN n.name AS name"
93
)
94
95
await driver.close()
96
97
asyncio.run(main())
98
```
99
100
## Architecture
101
102
The Neo4j Python driver follows a hierarchical architecture designed for scalability and flexibility:
103
104
- **Driver**: Top-level connection manager handling connection pooling, routing, and authentication. Supports both direct connections (BoltDriver) and cluster routing (Neo4jDriver).
105
- **Session**: Logical container for executing work, providing transaction management and causal consistency through bookmarks.
106
- **Transaction**: Unit of work that can be either auto-commit (via `run()`) or explicit (via `begin_transaction()`). Supports both read and write operations with automatic retry logic.
107
- **Result**: Iterator-like object for consuming query results, offering both streaming and eager consumption patterns.
108
109
This design enables efficient connection reuse, automatic failover in clustered environments, and provides both simple and advanced usage patterns through execute_query shortcuts and explicit transaction management.
110
111
## Capabilities
112
113
### Drivers & Connection
114
115
Core connection management through GraphDatabase factory methods and Driver classes, supporting both direct server connections and cluster routing with comprehensive configuration options.
116
117
```python { .api }
118
class GraphDatabase:
119
@staticmethod
120
def driver(uri: str, *, auth: Auth = None, **config) -> Driver: ...
121
122
@staticmethod
123
def bolt_driver(target: str, **config) -> BoltDriver: ...
124
125
@staticmethod
126
def neo4j_driver(*targets: str, routing_context: dict = None, **config) -> Neo4jDriver: ...
127
128
class Driver:
129
def session(**config) -> Session: ...
130
def execute_query(query: str, parameters: dict = None, **kwargs) -> tuple[list[Record], ResultSummary, list[str]]: ...
131
def close() -> None: ...
132
```
133
134
[Drivers & Connection](./drivers.md)
135
136
### Sessions
137
138
Session management providing contexts for executing work with transaction control, bookmark handling for causal consistency, and support for both read and write operations.
139
140
```python { .api }
141
class Session:
142
def run(query: str, parameters: dict = None, **kwargs) -> Result: ...
143
def execute_read(work: Callable, *args, **kwargs): ...
144
def execute_write(work: Callable, *args, **kwargs): ...
145
def begin_transaction(**config) -> Transaction: ...
146
def close() -> None: ...
147
```
148
149
[Sessions](./sessions.md)
150
151
### Transactions & Results
152
153
Transaction management and result handling supporting auto-commit transactions, explicit transactions with full ACID properties, and flexible result consumption patterns.
154
155
```python { .api }
156
class Transaction:
157
def run(query: str, parameters: dict = None, **kwparameters) -> Result: ...
158
def commit() -> None: ...
159
def rollback() -> None: ...
160
161
class Result:
162
def consume() -> ResultSummary: ...
163
def single(strict: bool = True) -> Record | None: ...
164
def data(*args) -> list[dict]: ...
165
def to_df() -> pandas.DataFrame: ...
166
```
167
168
[Transactions & Results](./transactions-results.md)
169
170
### Authentication
171
172
Authentication system supporting multiple authentication schemes including basic, Kerberos, bearer tokens, and custom authentication mechanisms.
173
174
```python { .api }
175
def basic_auth(user: str, password: str, realm: str = None) -> Auth: ...
176
def kerberos_auth(base64_encoded_ticket: str) -> Auth: ...
177
def bearer_auth(base64_encoded_token: str) -> Auth: ...
178
def custom_auth(principal: str, credentials: str, realm: str, scheme: str, **parameters) -> Auth: ...
179
180
class Auth:
181
scheme: str | None
182
principal: str | None
183
credentials: str | None
184
realm: str | None
185
```
186
187
[Authentication](./authentication.md)
188
189
### Data Types
190
191
Rich data type system including records, queries with metadata, bookmarks for causal consistency, graph data types (Node, Relationship, Path), temporal types (Date, DateTime, Time, Duration), spatial types (Point variants), and exception hierarchy for error handling.
192
193
```python { .api }
194
class Record:
195
def keys() -> tuple[str, ...]: ...
196
def values() -> tuple: ...
197
def get(key: str, default=None): ...
198
def data(*keys) -> dict: ...
199
200
class Query:
201
def __init__(text: str, metadata: dict = None, timeout: float = None): ...
202
text: str
203
metadata: dict | None
204
timeout: float | None
205
206
class Node:
207
element_id: str
208
labels: frozenset[str]
209
def get(name: str, default=None): ...
210
211
# Neo4j temporal types
212
class DateTime:
213
def __init__(year: int, month: int, day: int, hour: int = 0, ...): ...
214
year: int
215
month: int
216
nanosecond: int
217
218
# Spatial types
219
class Point:
220
srid: int | None
221
x: float
222
y: float
223
224
# Exception hierarchy
225
class Neo4jError(Exception):
226
code: str
227
message: str
228
```
229
230
[Data Types](./data-types.md)
231
232
### Configuration
233
234
Configuration management including SSL/TLS trust settings, connection pooling, timeout configuration, and cluster routing options.
235
236
```python { .api }
237
class TrustSystemCAs: ...
238
class TrustAll: ...
239
class TrustCustomCAs:
240
def __init__(*certs): ...
241
242
# Configuration constants
243
TRUST_SYSTEM_CA_SIGNED_CERTIFICATES: str
244
TRUST_ALL_CERTIFICATES: str
245
READ_ACCESS: str
246
WRITE_ACCESS: str
247
```
248
249
[Configuration](./configuration.md)