0
# Sessions
1
2
Session management providing contexts for executing work with transaction control, bookmark handling for causal consistency, and support for both read and write operations. Sessions manage the logical connection to the database and handle transaction lifecycle, retry logic, and connection pooling.
3
4
## Capabilities
5
6
### Session Class
7
8
Synchronous session providing the main interface for executing Cypher queries and managing transactions within a logical database connection context.
9
10
```python { .api }
11
class Session:
12
def run(
13
self,
14
query: str,
15
parameters: dict = None,
16
**kwargs
17
) -> Result:
18
"""
19
Run a Cypher query in an auto-commit transaction.
20
21
Parameters:
22
- query: Cypher query string
23
- parameters: Query parameters dictionary
24
- **kwargs: Additional query configuration options
25
26
Returns:
27
Result stream for consuming query results
28
"""
29
30
def execute_read(
31
self,
32
work: Callable[[ManagedTransaction], Any],
33
*args,
34
**kwargs
35
) -> Any:
36
"""
37
Execute a read transaction function with automatic retry.
38
39
Parameters:
40
- work: Transaction function taking ManagedTransaction parameter
41
- *args: Arguments to pass to transaction function
42
- **kwargs: Keyword arguments for transaction function
43
44
Returns:
45
Return value of the transaction function
46
"""
47
48
def execute_write(
49
self,
50
work: Callable[[ManagedTransaction], Any],
51
*args,
52
**kwargs
53
) -> Any:
54
"""
55
Execute a write transaction function with automatic retry.
56
57
Parameters:
58
- work: Transaction function taking ManagedTransaction parameter
59
- *args: Arguments to pass to transaction function
60
- **kwargs: Keyword arguments for transaction function
61
62
Returns:
63
Return value of the transaction function
64
"""
65
66
def begin_transaction(
67
self,
68
*,
69
metadata: dict = None,
70
timeout: float = None
71
) -> Transaction:
72
"""
73
Begin an explicit transaction for manual control.
74
75
Parameters:
76
- metadata: Transaction metadata dictionary
77
- timeout: Transaction timeout in seconds
78
79
Returns:
80
Transaction object for manual transaction management
81
"""
82
83
def close(self) -> None:
84
"""
85
Close the session and release resources.
86
Should be called when session is no longer needed.
87
"""
88
89
@property
90
def last_bookmarks(self) -> list[Bookmark]:
91
"""
92
Get bookmarks from the last completed transaction.
93
Used for causal consistency across sessions.
94
95
Returns:
96
List of bookmark objects
97
"""
98
```
99
100
Example usage:
101
102
```python
103
from neo4j import GraphDatabase, basic_auth
104
105
driver = GraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "password"))
106
107
# Using session context manager (recommended)
108
with driver.session() as session:
109
# Auto-commit transaction
110
result = session.run("CREATE (n:Person {name: $name}) RETURN n", name="Alice")
111
112
# Read transaction with retry
113
def read_people(tx):
114
result = tx.run("MATCH (n:Person) RETURN n.name AS name")
115
return [record["name"] for record in result]
116
117
names = session.execute_read(read_people)
118
119
# Write transaction with retry
120
def create_person(tx, name):
121
return tx.run("CREATE (n:Person {name: $name}) RETURN id(n)", name=name).single().value()
122
123
person_id = session.execute_write(create_person, "Bob")
124
125
# Manual transaction control
126
tx = session.begin_transaction()
127
try:
128
tx.run("CREATE (n:Person {name: $name})", name="Charlie")
129
tx.commit()
130
except Exception:
131
tx.rollback()
132
raise
133
```
134
135
### AsyncSession Class
136
137
Asynchronous session providing async versions of all session operations for non-blocking database interactions.
138
139
```python { .api }
140
class AsyncSession:
141
async def run(
142
self,
143
query: str,
144
parameters: dict = None,
145
**kwargs
146
) -> AsyncResult:
147
"""
148
Run a Cypher query in an async auto-commit transaction.
149
150
Parameters:
151
- query: Cypher query string
152
- parameters: Query parameters dictionary
153
- **kwargs: Additional query configuration options
154
155
Returns:
156
AsyncResult stream for consuming query results
157
"""
158
159
async def execute_read(
160
self,
161
work: Callable[[AsyncManagedTransaction], Awaitable[Any]],
162
*args,
163
**kwargs
164
) -> Any:
165
"""
166
Execute an async read transaction function with automatic retry.
167
168
Parameters:
169
- work: Async transaction function
170
- *args: Arguments to pass to transaction function
171
- **kwargs: Keyword arguments for transaction function
172
173
Returns:
174
Return value of the transaction function
175
"""
176
177
async def execute_write(
178
self,
179
work: Callable[[AsyncManagedTransaction], Awaitable[Any]],
180
*args,
181
**kwargs
182
) -> Any:
183
"""
184
Execute an async write transaction function with automatic retry.
185
186
Parameters:
187
- work: Async transaction function
188
- *args: Arguments to pass to transaction function
189
- **kwargs: Keyword arguments for transaction function
190
191
Returns:
192
Return value of the transaction function
193
"""
194
195
async def begin_transaction(
196
self,
197
*,
198
metadata: dict = None,
199
timeout: float = None
200
) -> AsyncTransaction:
201
"""
202
Begin an async explicit transaction.
203
204
Parameters:
205
- metadata: Transaction metadata dictionary
206
- timeout: Transaction timeout in seconds
207
208
Returns:
209
AsyncTransaction object for manual transaction management
210
"""
211
212
async def close(self) -> None:
213
"""
214
Asynchronously close the session and release resources.
215
"""
216
217
@property
218
def last_bookmarks(self) -> list[Bookmark]:
219
"""
220
Get bookmarks from the last completed transaction.
221
222
Returns:
223
List of bookmark objects for causal consistency
224
"""
225
```
226
227
Example async usage:
228
229
```python
230
import asyncio
231
from neo4j import AsyncGraphDatabase, basic_auth
232
233
async def example():
234
driver = AsyncGraphDatabase.driver("bolt://localhost:7687", auth=basic_auth("neo4j", "password"))
235
236
# Using async session context manager
237
async with driver.session() as session:
238
# Async auto-commit transaction
239
result = await session.run("CREATE (n:Person {name: $name}) RETURN n", name="Alice")
240
241
# Async read transaction
242
async def read_people(tx):
243
result = await tx.run("MATCH (n:Person) RETURN n.name AS name")
244
return [record["name"] async for record in result]
245
246
names = await session.execute_read(read_people)
247
248
# Async write transaction
249
async def create_person(tx, name):
250
result = await tx.run("CREATE (n:Person {name: $name}) RETURN id(n)", name=name)
251
record = await result.single()
252
return record.value()
253
254
person_id = await session.execute_write(create_person, "Bob")
255
256
# Manual async transaction
257
tx = await session.begin_transaction()
258
try:
259
await tx.run("CREATE (n:Person {name: $name})", name="Charlie")
260
await tx.commit()
261
except Exception:
262
await tx.rollback()
263
raise
264
265
await driver.close()
266
267
asyncio.run(example())
268
```
269
270
## Session Configuration
271
272
Sessions can be configured with various options when created from a driver:
273
274
```python
275
# Session with specific database
276
session = driver.session(database="mydb")
277
278
# Session with default access mode
279
session = driver.session(default_access_mode=neo4j.WRITE_ACCESS)
280
281
# Session with initial bookmarks for causal consistency
282
session = driver.session(bookmarks=[bookmark1, bookmark2])
283
284
# Session with custom bookmark manager
285
session = driver.session(bookmark_manager=custom_bookmark_manager)
286
287
# Session with session-level authentication
288
session = driver.session(auth=basic_auth("different_user", "password"))
289
```
290
291
## Transaction Functions
292
293
Transaction functions provide automatic retry logic for handling transient errors and are the recommended way to execute database operations:
294
295
```python
296
def create_friendship(tx, person1, person2):
297
"""Transaction function that creates a friendship relationship."""
298
query = """
299
MATCH (p1:Person {name: $name1}), (p2:Person {name: $name2})
300
CREATE (p1)-[:FRIENDS_WITH]->(p2)
301
RETURN p1.name, p2.name
302
"""
303
result = tx.run(query, name1=person1, name2=person2)
304
record = result.single()
305
return record.values()
306
307
# Execute with automatic retry
308
with driver.session() as session:
309
result = session.execute_write(create_friendship, "Alice", "Bob")
310
print(f"Created friendship: {result}")
311
```
312
313
## Causal Consistency
314
315
Sessions support causal consistency through bookmarks, ensuring read operations can see the effects of previous write operations:
316
317
```python
318
# Write in one session and capture bookmarks
319
with driver.session() as write_session:
320
write_session.run("CREATE (n:Person {name: 'Alice'})")
321
bookmarks = write_session.last_bookmarks
322
323
# Read from another session using bookmarks
324
with driver.session(bookmarks=bookmarks) as read_session:
325
result = read_session.run("MATCH (n:Person {name: 'Alice'}) RETURN n")
326
# This read will see the Alice node created above
327
```
328
329
## Types
330
331
```python { .api }
332
class Bookmark:
333
"""
334
Represents a bookmark for causal consistency.
335
Bookmarks are opaque values returned by transactions.
336
"""
337
338
class ManagedTransaction:
339
"""
340
Transaction managed by transaction functions.
341
Cannot be committed or rolled back manually.
342
"""
343
def run(
344
self,
345
query: str,
346
parameters: dict = None,
347
**kwparameters
348
) -> Result:
349
"""Run Cypher within the managed transaction."""
350
351
class AsyncManagedTransaction:
352
"""
353
Async transaction managed by transaction functions.
354
Cannot be committed or rolled back manually.
355
"""
356
async def run(
357
self,
358
query: str,
359
parameters: dict = None,
360
**kwparameters
361
) -> AsyncResult:
362
"""Run Cypher within the async managed transaction."""
363
```