0
# Session Operations
1
2
Session management for executing queries and managing database interactions with support for read/write modes and transaction handling.
3
4
## Capabilities
5
6
### Session Creation
7
8
Sessions are created from driver instances and provide the primary interface for query execution.
9
10
```typescript { .api }
11
interface Driver {
12
/** Create a new session with optional configuration */
13
session(config?: SessionConfig): Session;
14
15
/** Create a new reactive session with optional configuration */
16
rxSession(config?: SessionConfig): RxSession;
17
}
18
19
interface SessionConfig {
20
/** Default access mode for the session */
21
defaultAccessMode?: SessionMode;
22
23
/** Bookmarks for causal consistency */
24
bookmarks?: string | string[] | Bookmarks;
25
26
/** Target database name (Neo4j 4.0+) */
27
database?: string;
28
29
/** User to impersonate for queries */
30
impersonatedUser?: string;
31
32
/** Bookmark manager for automatic bookmark handling */
33
bookmarkManager?: BookmarkManager;
34
35
/** Session-level notification filtering */
36
notificationFilter?: NotificationFilter;
37
38
/** Session-level authentication override */
39
auth?: AuthToken | AuthTokenManager;
40
}
41
42
type SessionMode = "READ" | "WRITE";
43
```
44
45
**Usage Examples:**
46
47
```typescript
48
import { driver, auth, session } from "neo4j-driver";
49
50
const neo4jDriver = driver("neo4j://localhost:7687", auth.basic("neo4j", "password"));
51
52
// Default session
53
const defaultSession = neo4jDriver.session();
54
55
// Read-only session
56
const readSession = neo4jDriver.session({
57
defaultAccessMode: session.READ,
58
database: "mydb"
59
});
60
61
// Session with bookmarks
62
const bookmarkedSession = neo4jDriver.session({
63
bookmarks: ["bookmark:12345"],
64
database: "analytics"
65
});
66
```
67
68
### Query Execution
69
70
Execute Cypher queries directly on sessions with parameter support.
71
72
```typescript { .api }
73
interface Session {
74
/**
75
* Run a Cypher query with optional parameters
76
* @param query - The Cypher query string
77
* @param parameters - Query parameters as key-value pairs
78
* @returns Promise resolving to query result
79
*/
80
run(query: string, parameters?: Parameters): Promise<Result>;
81
82
/** Get the last bookmark for this session */
83
lastBookmark(): string;
84
85
/** Get all bookmarks for this session */
86
lastBookmarks(): string[];
87
88
/** Close the session and release resources */
89
close(): Promise<void>;
90
}
91
92
type Parameters = Record<string, any>;
93
```
94
95
**Usage Examples:**
96
97
```typescript
98
const session = neo4jDriver.session();
99
100
try {
101
// Simple query
102
const result1 = await session.run("MATCH (n:Person) RETURN n LIMIT 10");
103
104
// Parameterized query
105
const result2 = await session.run(
106
"CREATE (p:Person {name: $name, age: $age}) RETURN p",
107
{ name: "Alice", age: 30 }
108
);
109
110
// Complex query with multiple parameters
111
const result3 = await session.run(`
112
MATCH (p:Person {name: $name})
113
SET p.lastLogin = $timestamp
114
RETURN p
115
`, {
116
name: "Alice",
117
timestamp: new Date().toISOString()
118
});
119
120
console.log(`Created ${result2.summary.counters.nodesCreated} nodes`);
121
} finally {
122
await session.close();
123
}
124
```
125
126
### Managed Transactions
127
128
Managed transactions with automatic retry logic for robust database operations.
129
130
```typescript { .api }
131
interface Session {
132
/**
133
* Execute a read transaction with automatic retry logic
134
* @param work - Function containing read operations
135
* @param config - Optional transaction configuration
136
* @returns Promise resolving to the work function result
137
*/
138
executeRead<T>(
139
work: (tx: ManagedTransaction) => Promise<T>,
140
config?: TransactionConfig
141
): Promise<T>;
142
143
/**
144
* Execute a write transaction with automatic retry logic
145
* @param work - Function containing write operations
146
* @param config - Optional transaction configuration
147
* @returns Promise resolving to the work function result
148
*/
149
executeWrite<T>(
150
work: (tx: ManagedTransaction) => Promise<T>,
151
config?: TransactionConfig
152
): Promise<T>;
153
}
154
155
interface ManagedTransaction {
156
/** Run a query within the managed transaction */
157
run(query: string, parameters?: Parameters): Promise<Result>;
158
}
159
160
interface TransactionConfig {
161
/** Transaction timeout in milliseconds */
162
timeout?: number;
163
164
/** Transaction metadata for monitoring */
165
metadata?: Record<string, any>;
166
}
167
```
168
169
**Usage Examples:**
170
171
```typescript
172
const session = neo4jDriver.session();
173
174
try {
175
// Read transaction
176
const people = await session.executeRead(async tx => {
177
const result = await tx.run("MATCH (p:Person) RETURN p.name AS name");
178
return result.records.map(record => record.get("name"));
179
});
180
181
// Write transaction with retry logic
182
const created = await session.executeWrite(async tx => {
183
const result = await tx.run(`
184
CREATE (p:Person {name: $name, id: randomUUID()})
185
RETURN p.id AS id
186
`, { name: "Bob" });
187
188
return result.records[0].get("id");
189
}, {
190
timeout: 30000, // 30 seconds
191
metadata: { operation: "create_person" }
192
});
193
194
console.log(`Created person with ID: ${created}`);
195
} finally {
196
await session.close();
197
}
198
```
199
200
### Explicit Transactions
201
202
Manual transaction management with full control over commit and rollback.
203
204
```typescript { .api }
205
interface Session {
206
/**
207
* Begin an explicit transaction
208
* @param config - Optional transaction configuration
209
* @returns Promise resolving to transaction instance
210
*/
211
beginTransaction(config?: TransactionConfig): Promise<Transaction>;
212
}
213
214
interface Transaction {
215
/** Run a query within the transaction */
216
run(query: string, parameters?: Parameters): Promise<Result>;
217
218
/** Commit the transaction */
219
commit(): Promise<void>;
220
221
/** Rollback the transaction */
222
rollback(): Promise<void>;
223
224
/** Check if the transaction is still open */
225
isOpen(): boolean;
226
}
227
```
228
229
**Usage Examples:**
230
231
```typescript
232
const session = neo4jDriver.session();
233
const tx = await session.beginTransaction();
234
235
try {
236
// Multiple operations in single transaction
237
await tx.run("CREATE (p:Person {name: $name})", { name: "Charlie" });
238
239
const result = await tx.run(`
240
MATCH (p:Person {name: $name})
241
CREATE (p)-[:WORKS_FOR]->(c:Company {name: $company})
242
RETURN c
243
`, { name: "Charlie", company: "Acme Corp" });
244
245
// Commit if all operations succeed
246
await tx.commit();
247
console.log("Transaction committed successfully");
248
} catch (error) {
249
// Rollback on any error
250
await tx.rollback();
251
console.error("Transaction rolled back:", error.message);
252
} finally {
253
await session.close();
254
}
255
```
256
257
### Result Processing
258
259
Query results provide access to records and execution metadata.
260
261
```typescript { .api }
262
interface Result {
263
/** Array of result records */
264
records: Record[];
265
266
/** Query execution summary */
267
summary: ResultSummary;
268
269
/** Column keys from the query */
270
keys: string[];
271
}
272
273
interface Record {
274
/** Get field value by key */
275
get(key: string): any;
276
277
/** Get field value by index */
278
get(index: number): any;
279
280
/** Check if field exists */
281
has(key: string): boolean;
282
283
/** Get all field keys */
284
keys: string[];
285
286
/** Get record length */
287
length: number;
288
289
/** Convert record to plain object */
290
toObject(): Record<string, any>;
291
}
292
293
interface ResultSummary {
294
/** Query that was executed */
295
query: Query;
296
297
/** Query execution statistics */
298
counters: QueryStatistics;
299
300
/** Query execution plan (if available) */
301
plan?: Plan;
302
303
/** Profiled execution plan (if available) */
304
profile?: ProfiledPlan;
305
306
/** Execution notifications */
307
notifications: Notification[];
308
309
/** Server information */
310
server: ServerInfo;
311
312
/** Result availability information */
313
resultAvailableAfter: Integer;
314
315
/** Result consumption time */
316
resultConsumedAfter: Integer;
317
318
/** Database name where query was executed */
319
database: { name?: string };
320
}
321
```
322
323
**Usage Examples:**
324
325
```typescript
326
const session = neo4jDriver.session();
327
328
try {
329
const result = await session.run(`
330
MATCH (p:Person)
331
WHERE p.age > $minAge
332
RETURN p.name AS name, p.age AS age
333
ORDER BY p.age DESC
334
`, { minAge: 25 });
335
336
// Process records
337
result.records.forEach(record => {
338
console.log(`${record.get("name")} is ${record.get("age")} years old`);
339
340
// Alternative access methods
341
console.log(`${record.get(0)} is ${record.get(1)} years old`);
342
343
// Convert to object
344
const person = record.toObject();
345
console.log(person); // { name: "Alice", age: 30 }
346
});
347
348
// Examine summary
349
console.log(`Query returned ${result.records.length} records`);
350
console.log(`Query executed in ${result.summary.resultAvailableAfter} ms`);
351
352
if (result.summary.notifications.length > 0) {
353
result.summary.notifications.forEach(notification => {
354
console.warn(`Warning: ${notification.description}`);
355
});
356
}
357
} finally {
358
await session.close();
359
}
360
```
361
362
### Session Access Modes
363
364
Constants for controlling session read/write behavior.
365
366
```typescript { .api }
367
declare const session: {
368
/** Read-only access mode */
369
READ: "READ";
370
371
/** Read-write access mode */
372
WRITE: "WRITE";
373
};
374
```