0
# Configuration
1
2
Configuration management including SSL/TLS trust settings, connection pooling, timeout configuration, and cluster routing options. The configuration system provides comprehensive control over driver behavior, security settings, and performance tuning.
3
4
## Capabilities
5
6
### Trust Store Configuration
7
8
SSL/TLS certificate trust configuration for secure connections to Neo4j servers.
9
10
```python { .api }
11
class TrustSystemCAs:
12
"""
13
Trust system certificate authorities (default behavior).
14
Uses the operating system's certificate store to validate server certificates.
15
"""
16
17
class TrustAll:
18
"""
19
Trust all certificates (insecure - for development only).
20
Accepts any server certificate without validation.
21
WARNING: Should never be used in production environments.
22
"""
23
24
class TrustCustomCAs:
25
"""
26
Trust custom certificate authorities.
27
Allows specification of custom certificate files for validation.
28
"""
29
def __init__(self, *certs: str):
30
"""
31
Initialize with custom certificate files.
32
33
Parameters:
34
- *certs: Paths to certificate files to trust
35
"""
36
```
37
38
Trust configuration examples:
39
40
```python
41
from neo4j import GraphDatabase, TrustSystemCAs, TrustAll, TrustCustomCAs, basic_auth
42
43
# Use system certificate authorities (default)
44
driver = GraphDatabase.driver(
45
"bolt+s://secure.neo4j.com:7687",
46
auth=basic_auth("neo4j", "password"),
47
trust=TrustSystemCAs()
48
)
49
50
# Development only - trust all certificates (insecure)
51
driver = GraphDatabase.driver(
52
"bolt+s://localhost:7687",
53
auth=basic_auth("neo4j", "password"),
54
trust=TrustAll()
55
)
56
57
# Trust custom certificate authorities
58
driver = GraphDatabase.driver(
59
"bolt+s://internal.company.com:7687",
60
auth=basic_auth("neo4j", "password"),
61
trust=TrustCustomCAs("/path/to/company-ca.pem", "/path/to/root-ca.pem")
62
)
63
64
# Using trust constants
65
import neo4j
66
67
driver = GraphDatabase.driver(
68
"bolt+s://neo4j.com:7687",
69
auth=basic_auth("neo4j", "password"),
70
trust=neo4j.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES
71
)
72
```
73
74
### Connection Pool Configuration
75
76
Driver configuration for connection pooling, timeouts, and connection management.
77
78
```python
79
from neo4j import GraphDatabase, basic_auth
80
81
driver = GraphDatabase.driver(
82
"bolt://localhost:7687",
83
auth=basic_auth("neo4j", "password"),
84
85
# Connection pool settings
86
max_connection_pool_size=50, # Maximum connections in pool
87
max_connection_lifetime=30 * 60, # 30 minutes in seconds
88
connection_acquisition_timeout=60.0, # 60 seconds
89
90
# Socket settings
91
connection_timeout=30.0, # Connection establishment timeout
92
max_transaction_retry_time=30.0, # Transaction retry timeout
93
94
# Encryption settings
95
encrypted=True, # Force encryption
96
trust=neo4j.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES,
97
98
# User agent customization
99
user_agent="MyApplication/1.0",
100
101
# Resolver for custom address resolution
102
resolver=custom_resolver_function,
103
104
# Keep alive settings
105
keep_alive=True,
106
107
# Update routing table settings
108
update_routing_table_timeout=30.0
109
)
110
```
111
112
### Notification Configuration
113
114
Configuration for controlling server notifications and their severity levels.
115
116
```python { .api }
117
class NotificationMinimumSeverity:
118
"""Enum for minimum notification severity levels."""
119
OFF: str # Disable all notifications
120
WARNING: str # Only warning and higher severity
121
INFORMATION: str # All notifications (default)
122
123
class NotificationSeverity:
124
"""Enum for notification severity levels."""
125
WARNING: str # Warning severity
126
INFORMATION: str # Information severity
127
UNKNOWN: str # Unknown severity
128
129
class NotificationCategory:
130
"""Enum for notification categories."""
131
# Various notification categories for different types of server messages
132
```
133
134
Notification configuration example:
135
136
```python
137
from neo4j import GraphDatabase, NotificationMinimumSeverity, basic_auth
138
139
# Configure notifications
140
driver = GraphDatabase.driver(
141
"bolt://localhost:7687",
142
auth=basic_auth("neo4j", "password"),
143
notifications_min_severity=NotificationMinimumSeverity.WARNING,
144
notifications_disabled_categories=[
145
"UNSUPPORTED", # Disable unsupported feature warnings
146
"PERFORMANCE" # Disable performance warnings
147
]
148
)
149
150
# Check notifications in results
151
with driver.session() as session:
152
result = session.run("MATCH (n) RETURN n")
153
summary = result.consume()
154
155
for notification in summary.notifications:
156
print(f"Severity: {notification.severity}")
157
print(f"Category: {notification.category}")
158
print(f"Title: {notification.title}")
159
print(f"Description: {notification.description}")
160
```
161
162
### Routing Configuration
163
164
Configuration for cluster routing and load balancing in Neo4j clusters.
165
166
```python { .api }
167
class RoutingControl:
168
"""Enum for controlling query routing in clusters."""
169
READ: str # Route to read replicas
170
WRITE: str # Route to write servers (default)
171
```
172
173
Cluster routing configuration:
174
175
```python
176
from neo4j import GraphDatabase, RoutingControl, basic_auth
177
178
# Cluster driver with routing configuration
179
driver = GraphDatabase.neo4j_driver(
180
"server1.cluster.com:7687",
181
"server2.cluster.com:7687",
182
"server3.cluster.com:7687",
183
auth=basic_auth("neo4j", "password"),
184
185
# Routing context for cluster discovery
186
routing_context={
187
"region": "us-west-2",
188
"zone": "us-west-2a",
189
"policy": "datacenter_local"
190
},
191
192
# Routing table refresh settings
193
max_connection_lifetime=3600, # 1 hour
194
update_routing_table_timeout=30.0 # 30 seconds
195
)
196
197
# Execute queries with routing control
198
with driver.session() as session:
199
# Write operation (routed to write servers)
200
session.execute_write(lambda tx: tx.run("CREATE (n:Person {name: 'Alice'})"))
201
202
# Read operation (routed to read replicas)
203
def read_people(tx):
204
return tx.run("MATCH (n:Person) RETURN n.name AS name").data()
205
206
people = session.execute_read(read_people)
207
```
208
209
### Database Configuration
210
211
Configuration for multi-database support and database selection.
212
213
```python
214
from neo4j import GraphDatabase, basic_auth
215
216
# Default database constants
217
import neo4j
218
print(neo4j.DEFAULT_DATABASE) # None (uses server default)
219
print(neo4j.SYSTEM_DATABASE) # "system"
220
221
driver = GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "password"))
222
223
# Sessions with specific databases
224
with driver.session(database="myapp") as session:
225
session.run("CREATE (n:User {name: 'Alice'})")
226
227
with driver.session(database="analytics") as session:
228
session.run("CREATE (n:Event {type: 'login'})")
229
230
with driver.session(database=neo4j.SYSTEM_DATABASE) as session:
231
result = session.run("SHOW DATABASES")
232
for record in result:
233
print(record["name"])
234
```
235
236
### Access Mode Configuration
237
238
Configuration for read/write access control and session behavior.
239
240
```python { .api }
241
# Access mode constants
242
READ_ACCESS: str = "READ"
243
WRITE_ACCESS: str = "WRITE"
244
```
245
246
Access mode configuration:
247
248
```python
249
from neo4j import GraphDatabase, READ_ACCESS, WRITE_ACCESS, basic_auth
250
251
driver = GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "password"))
252
253
# Read-only session
254
with driver.session(default_access_mode=READ_ACCESS) as session:
255
# Only read operations allowed
256
result = session.run("MATCH (n:Person) RETURN n.name")
257
258
# Write session (default)
259
with driver.session(default_access_mode=WRITE_ACCESS) as session:
260
session.run("CREATE (n:Person {name: 'Bob'})")
261
```
262
263
### Advanced Configuration Options
264
265
Comprehensive driver configuration with all available options:
266
267
```python
268
from neo4j import GraphDatabase, basic_auth, TrustSystemCAs
269
270
def custom_resolver(address):
271
"""Custom address resolver for service discovery."""
272
# Implement custom DNS resolution logic
273
return resolved_addresses
274
275
driver = GraphDatabase.driver(
276
"neo4j://cluster.example.com:7687",
277
auth=basic_auth("neo4j", "password"),
278
279
# Connection settings
280
max_connection_pool_size=100,
281
max_connection_lifetime=1800, # 30 minutes
282
connection_acquisition_timeout=120.0, # 2 minutes
283
connection_timeout=30.0,
284
285
# Transaction settings
286
max_transaction_retry_time=30.0,
287
default_access_mode=WRITE_ACCESS,
288
289
# Security settings
290
encrypted=True,
291
trust=TrustSystemCAs(),
292
293
# Notification settings
294
notifications_min_severity="WARNING",
295
notifications_disabled_categories=["PERFORMANCE"],
296
297
# Routing settings (for cluster drivers)
298
routing_context={"region": "us-east-1"},
299
update_routing_table_timeout=30.0,
300
301
# Custom settings
302
user_agent="MyApp/2.0 (Production)",
303
resolver=custom_resolver,
304
keep_alive=True,
305
306
# Session defaults
307
database="production",
308
bookmarks=None,
309
310
# Logging and debugging
311
# log_level="DEBUG" # Not directly available, use Python logging
312
)
313
```
314
315
### Environment-Based Configuration
316
317
Configuration using environment variables and configuration files:
318
319
```python
320
import os
321
from neo4j import GraphDatabase, basic_auth, TrustSystemCAs
322
323
class Neo4jConfig:
324
def __init__(self):
325
# Connection settings from environment
326
self.uri = os.getenv("NEO4J_URI", "bolt://localhost:7687")
327
self.username = os.getenv("NEO4J_USERNAME", "neo4j")
328
self.password = os.getenv("NEO4J_PASSWORD")
329
self.database = os.getenv("NEO4J_DATABASE", None)
330
331
# Pool settings
332
self.max_pool_size = int(os.getenv("NEO4J_MAX_POOL_SIZE", "50"))
333
self.max_lifetime = int(os.getenv("NEO4J_MAX_LIFETIME", "3600"))
334
335
# Security settings
336
self.encrypted = os.getenv("NEO4J_ENCRYPTED", "true").lower() == "true"
337
self.trust_level = os.getenv("NEO4J_TRUST", "SYSTEM_CA")
338
339
if not self.password:
340
raise ValueError("NEO4J_PASSWORD environment variable required")
341
342
def create_driver(self):
343
trust_config = TrustSystemCAs() # Default to system CAs
344
345
return GraphDatabase.driver(
346
self.uri,
347
auth=basic_auth(self.username, self.password),
348
max_connection_pool_size=self.max_pool_size,
349
max_connection_lifetime=self.max_lifetime,
350
encrypted=self.encrypted,
351
trust=trust_config
352
)
353
354
# Usage
355
config = Neo4jConfig()
356
driver = config.create_driver()
357
```
358
359
### Performance Tuning
360
361
Configuration for optimal performance in different scenarios:
362
363
```python
364
from neo4j import GraphDatabase, basic_auth
365
366
# High-throughput configuration
367
high_throughput_driver = GraphDatabase.driver(
368
"bolt://localhost:7687",
369
auth=basic_auth("neo4j", "password"),
370
max_connection_pool_size=200, # Large pool for concurrent requests
371
connection_acquisition_timeout=5.0, # Fast timeout to avoid blocking
372
max_connection_lifetime=300, # Short lifetime for refresh
373
max_transaction_retry_time=5.0 # Quick retry for high throughput
374
)
375
376
# Long-running batch processing configuration
377
batch_driver = GraphDatabase.driver(
378
"bolt://localhost:7687",
379
auth=basic_auth("neo4j", "password"),
380
max_connection_pool_size=10, # Fewer connections for batch jobs
381
connection_acquisition_timeout=300.0, # Longer timeout for availability
382
max_connection_lifetime=7200, # 2 hours for stable connections
383
max_transaction_retry_time=300.0 # Longer retry for batch operations
384
)
385
386
# Development/testing configuration
387
dev_driver = GraphDatabase.driver(
388
"bolt://localhost:7687",
389
auth=basic_auth("neo4j", "password"),
390
max_connection_pool_size=5, # Small pool for development
391
connection_acquisition_timeout=30.0,
392
max_connection_lifetime=600, # 10 minutes
393
encrypted=False # Disable encryption for local dev
394
)
395
```
396
397
## Configuration Constants
398
399
```python { .api }
400
# Trust configuration constants
401
TRUST_SYSTEM_CA_SIGNED_CERTIFICATES: str = "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES"
402
TRUST_ALL_CERTIFICATES: str = "TRUST_ALL_CERTIFICATES"
403
404
# Access mode constants
405
READ_ACCESS: str = "READ"
406
WRITE_ACCESS: str = "WRITE"
407
408
# Database constants
409
DEFAULT_DATABASE: None = None
410
SYSTEM_DATABASE: str = "system"
411
```
412
413
### Utility Functions
414
415
```python { .api }
416
def get_user_agent() -> str:
417
"""
418
Get the driver's default user agent string.
419
420
Returns:
421
Default user agent string sent to the server
422
"""
423
424
__version__: str
425
"""Driver version string."""
426
```
427
428
Example utility usage:
429
430
```python
431
import neo4j
432
433
print(f"Neo4j Python Driver version: {neo4j.__version__}")
434
print(f"User agent: {neo4j.get_user_agent()}")
435
436
# Custom user agent
437
custom_agent = f"MyApp/1.0 {neo4j.get_user_agent()}"
438
driver = GraphDatabase.driver(
439
"bolt://localhost:7687",
440
auth=basic_auth("neo4j", "password"),
441
user_agent=custom_agent
442
)
443
```