0
# Graph Database Operations
1
2
Core graph database functionality providing transaction management, query execution, and direct access to the graph data model with comprehensive ACID transaction support.
3
4
## Capabilities
5
6
### Graph Database Service
7
8
Represents a graph database instance and provides the primary interface for creating transactions and executing queries.
9
10
```java { .api }
11
/**
12
* Represents a graph database and creates transactions
13
*/
14
public interface GraphDatabaseService {
15
16
/**
17
* Begin a new transaction with default timeout
18
* @return New transaction instance
19
*/
20
Transaction beginTx();
21
22
/**
23
* Begin a new transaction with specified timeout
24
* @param timeout Transaction timeout value
25
* @param unit Time unit for timeout
26
* @return New transaction instance
27
*/
28
Transaction beginTx(long timeout, TimeUnit unit);
29
30
/**
31
* Execute a Cypher query in an auto-commit transaction
32
* @param query Cypher query string
33
* @throws TransactionFailureException if query execution fails
34
*/
35
void executeTransactionally(String query);
36
37
/**
38
* Execute a Cypher query with parameters in an auto-commit transaction
39
* @param query Cypher query string
40
* @param parameters Query parameters map
41
* @throws TransactionFailureException if query execution fails
42
*/
43
void executeTransactionally(String query, Map<String, Object> parameters);
44
45
/**
46
* Execute a Cypher query and transform results in an auto-commit transaction
47
* @param query Cypher query string
48
* @param parameters Query parameters map
49
* @param resultTransformer Function to transform query results
50
* @return Transformed result
51
* @throws TransactionFailureException if query execution fails
52
*/
53
<T> T executeTransactionally(String query, Map<String, Object> parameters,
54
ResultTransformer<T> resultTransformer);
55
56
/**
57
* Check if the database is available for operations
58
* @return true if database is available, false otherwise
59
*/
60
boolean isAvailable();
61
62
/**
63
* Get the name of this database
64
* @return Database name
65
*/
66
String databaseName();
67
68
}
69
```
70
71
**Usage Examples:**
72
73
```java
74
import org.neo4j.graphdb.GraphDatabaseService;
75
import org.neo4j.graphdb.Transaction;
76
import java.util.Map;
77
import java.util.concurrent.TimeUnit;
78
79
// Check database availability
80
GraphDatabaseService graphDb = managementService.database("neo4j");
81
if (graphDb.isAvailable()) {
82
System.out.println("Database " + graphDb.databaseName() + " is available");
83
}
84
85
// Simple auto-commit query execution
86
graphDb.executeTransactionally("CREATE (p:Person {name: 'Alice', age: 30})");
87
88
// Query with parameters
89
Map<String, Object> params = Map.of("name", "Bob", "age", 25);
90
graphDb.executeTransactionally(
91
"CREATE (p:Person {name: $name, age: $age})",
92
params
93
);
94
95
// Query with result transformation
96
List<String> names = graphDb.executeTransactionally(
97
"MATCH (p:Person) RETURN p.name as name",
98
Map.of(),
99
result -> {
100
List<String> nameList = new ArrayList<>();
101
while (result.hasNext()) {
102
nameList.add((String) result.next().get("name"));
103
}
104
return nameList;
105
}
106
);
107
108
// Manual transaction management
109
try (Transaction tx = graphDb.beginTx(30, TimeUnit.SECONDS)) {
110
// Perform operations within transaction
111
tx.commit();
112
}
113
```
114
115
### Transaction Management
116
117
ACID-compliant transaction interface providing full control over database operations with commit, rollback, and resource management capabilities.
118
119
```java { .api }
120
/**
121
* Programmatically handled transaction with ACID properties
122
* Implements AutoCloseable for try-with-resources usage
123
*/
124
public interface Transaction extends AutoCloseable {
125
126
/**
127
* Commit all changes made in this transaction
128
* @throws TransactionFailureException if commit fails
129
*/
130
void commit();
131
132
/**
133
* Rollback all changes made in this transaction
134
*/
135
void rollback();
136
137
/**
138
* Close the transaction, rolling back if not already committed
139
*/
140
@Override
141
void close();
142
143
/**
144
* Terminate the transaction forcibly
145
* This will interrupt any running operations
146
*/
147
void terminate();
148
149
/**
150
* Create a new node without labels
151
* @return New node instance
152
*/
153
Node createNode();
154
155
/**
156
* Create a new node with specified labels
157
* @param labels Labels to assign to the new node
158
* @return New node instance
159
*/
160
Node createNode(Label... labels);
161
162
/**
163
* Get node by ID
164
* @param id Node ID
165
* @return Node instance
166
* @throws NotFoundException if node doesn't exist
167
*/
168
Node getNodeById(long id);
169
170
/**
171
* Get relationship by ID
172
* @param id Relationship ID
173
* @return Relationship instance
174
* @throws NotFoundException if relationship doesn't exist
175
*/
176
Relationship getRelationshipById(long id);
177
178
/**
179
* Find nodes with specific label
180
* @param label Label to search for
181
* @return Iterable of matching nodes
182
*/
183
ResourceIterable<Node> findNodes(Label label);
184
185
/**
186
* Find nodes with label and property
187
* @param label Label to search for
188
* @param key Property key
189
* @param value Property value
190
* @return Iterable of matching nodes
191
*/
192
ResourceIterable<Node> findNodes(Label label, String key, Object value);
193
194
/**
195
* Execute a Cypher query within this transaction
196
* @param query Cypher query string
197
* @return Query result
198
*/
199
Result execute(String query);
200
201
/**
202
* Execute a Cypher query with parameters within this transaction
203
* @param query Cypher query string
204
* @param parameters Query parameters map
205
* @return Query result
206
*/
207
Result execute(String query, Map<String, Object> parameters);
208
209
/**
210
* Acquire a write lock on an entity
211
* @param entity Entity to lock (Node or Relationship)
212
* @return Lock instance
213
*/
214
Lock acquireWriteLock(Entity entity);
215
216
/**
217
* Acquire a read lock on an entity
218
* @param entity Entity to lock (Node or Relationship)
219
* @return Lock instance
220
*/
221
Lock acquireReadLock(Entity entity);
222
223
/**
224
* Get node by element ID (preferred over getNodeById)
225
* @param elementId Element ID of the node
226
* @return Node instance
227
* @throws NotFoundException if node doesn't exist
228
*/
229
Node getNodeByElementId(String elementId);
230
231
/**
232
* Get relationship by element ID (preferred over getRelationshipById)
233
* @param elementId Element ID of the relationship
234
* @return Relationship instance
235
* @throws NotFoundException if relationship doesn't exist
236
*/
237
Relationship getRelationshipByElementId(String elementId);
238
239
/**
240
* Find a single node with specific label and property
241
* @param label Label to search for
242
* @param key Property key
243
* @param value Property value
244
* @return Single matching node, or null if not found
245
*/
246
Node findNode(Label label, String key, Object value);
247
248
/**
249
* Find nodes with specific label (returns iterator for resource management)
250
* @param label Label to search for
251
* @return Resource iterator of matching nodes
252
*/
253
ResourceIterator<Node> findNodes(Label label);
254
255
/**
256
* Get all labels currently in use in the database
257
* @return Iterable of labels in use
258
*/
259
Iterable<Label> getAllLabelsInUse();
260
261
/**
262
* Get all relationship types currently in use in the database
263
* @return Iterable of relationship types in use
264
*/
265
Iterable<RelationshipType> getAllRelationshipTypesInUse();
266
267
/**
268
* Get all property keys currently in use in the database
269
* @return Iterable of property keys
270
*/
271
Iterable<String> getAllPropertyKeys();
272
273
/**
274
* Create a traversal description for this transaction
275
* @return New traversal description
276
*/
277
TraversalDescription traversalDescription();
278
279
/**
280
* Create a bidirectional traversal description for this transaction
281
* @return New bidirectional traversal description
282
*/
283
BidirectionalTraversalDescription bidirectionalTraversalDescription();
284
285
/**
286
* Find all nodes in the database
287
* @return ResourceIterator of all nodes
288
*/
289
ResourceIterator<Node> getAllNodes();
290
291
/**
292
* Find all relationships in the database
293
* @return ResourceIterator of all relationships
294
*/
295
ResourceIterator<Relationship> getAllRelationships();
296
297
/**
298
* Find nodes with label and string search
299
* @param label Label to search for
300
* @param key Property key
301
* @param template Search template
302
* @param searchMode Search mode (EXACT, PREFIX, SUFFIX, CONTAINS)
303
* @return ResourceIterator of matching nodes
304
*/
305
ResourceIterator<Node> findNodes(Label label, String key, String template, StringSearchMode searchMode);
306
307
/**
308
* Find nodes with multiple properties
309
* @param label Label to search for
310
* @param propertyValues Map of property key-value pairs
311
* @return ResourceIterator of matching nodes
312
*/
313
ResourceIterator<Node> findNodes(Label label, Map<String, Object> propertyValues);
314
315
/**
316
* Find nodes with two properties
317
* @param label Label to search for
318
* @param key1 First property key
319
* @param value1 First property value
320
* @param key2 Second property key
321
* @param value2 Second property value
322
* @return ResourceIterator of matching nodes
323
*/
324
ResourceIterator<Node> findNodes(Label label, String key1, Object value1, String key2, Object value2);
325
326
/**
327
* Find relationships by type and property
328
* @param relationshipType Relationship type to search for
329
* @param key Property key
330
* @param value Property value
331
* @return ResourceIterator of matching relationships
332
*/
333
ResourceIterator<Relationship> findRelationships(RelationshipType relationshipType, String key, Object value);
334
335
/**
336
* Find single relationship by type and property
337
* @param relationshipType Relationship type to search for
338
* @param key Property key
339
* @param value Property value
340
* @return Single matching relationship, or null if not found
341
*/
342
Relationship findRelationship(RelationshipType relationshipType, String key, Object value);
343
344
/**
345
* Get the database's schema management interface
346
* @return Schema management interface
347
*/
348
Schema schema();
349
}
350
351
/**
352
* String search modes for text-based property queries
353
*/
354
enum StringSearchMode {
355
EXACT, // Exact string match
356
PREFIX, // Starts with the given string
357
SUFFIX, // Ends with the given string
358
CONTAINS // Contains the given string
359
}
360
361
/**
362
* Auto-closeable iterator for graph database resources
363
*/
364
interface ResourceIterator<T> extends Iterator<T>, AutoCloseable {
365
/**
366
* Close the iterator and release associated resources
367
*/
368
void close();
369
}
370
```
371
372
**Usage Examples:**
373
374
```java
375
import org.neo4j.graphdb.Transaction;
376
import org.neo4j.graphdb.Node;
377
import org.neo4j.graphdb.Label;
378
import org.neo4j.graphdb.Result;
379
import static org.neo4j.graphdb.Label.label;
380
381
// Basic transaction usage with try-with-resources
382
try (Transaction tx = graphDb.beginTx()) {
383
// Create nodes and relationships
384
Node alice = tx.createNode(label("Person"));
385
alice.setProperty("name", "Alice");
386
alice.setProperty("age", 30);
387
388
Node bob = tx.createNode(label("Person"));
389
bob.setProperty("name", "Bob");
390
391
// Create relationship
392
alice.createRelationshipTo(bob, RelationshipType.withName("KNOWS"));
393
394
tx.commit();
395
} // Transaction automatically closed
396
397
// Query execution within transaction
398
try (Transaction tx = graphDb.beginTx()) {
399
Result result = tx.execute("MATCH (p:Person) RETURN p.name, p.age");
400
while (result.hasNext()) {
401
Map<String, Object> row = result.next();
402
System.out.println("Person: " + row.get("p.name") + ", Age: " + row.get("p.age"));
403
}
404
tx.commit();
405
}
406
407
// Node finding operations
408
try (Transaction tx = graphDb.beginTx()) {
409
// Find all Person nodes
410
ResourceIterable<Node> persons = tx.findNodes(label("Person"));
411
for (Node person : persons) {
412
System.out.println("Found person: " + person.getProperty("name"));
413
}
414
415
// Find specific person
416
ResourceIterable<Node> alices = tx.findNodes(label("Person"), "name", "Alice");
417
Node alice = alices.iterator().next();
418
419
tx.commit();
420
}
421
422
// Lock management for concurrent access
423
try (Transaction tx = graphDb.beginTx()) {
424
Node node = tx.getNodeById(123);
425
Lock lock = tx.acquireWriteLock(node);
426
try {
427
// Perform operations requiring exclusive access
428
node.setProperty("lastModified", System.currentTimeMillis());
429
} finally {
430
lock.release();
431
}
432
tx.commit();
433
}
434
435
// Error handling and rollback
436
try (Transaction tx = graphDb.beginTx()) {
437
try {
438
// Risky operations
439
Node node = tx.createNode();
440
node.setProperty("test", someComplexOperation());
441
tx.commit();
442
} catch (Exception e) {
443
tx.rollback();
444
throw e;
445
}
446
}
447
```
448
449
### Lock Management
450
451
Locking interface for managing concurrent access to graph entities within transactions.
452
453
```java { .api }
454
/**
455
* Lock for controlling concurrent access to entities
456
*/
457
public interface Lock {
458
/**
459
* Release this lock
460
*/
461
void release();
462
}
463
```
464
465
### Resource Management
466
467
Resource management interfaces for handling query results and iterables that need proper cleanup.
468
469
```java { .api }
470
/**
471
* Iterable that manages resources and must be properly closed
472
*/
473
public interface ResourceIterable<T> extends Iterable<T>, AutoCloseable {
474
/**
475
* Close any resources associated with this iterable
476
*/
477
@Override
478
void close();
479
}
480
481
/**
482
* Iterator that manages resources and must be properly closed
483
*/
484
public interface ResourceIterator<T> extends Iterator<T>, AutoCloseable {
485
/**
486
* Close any resources associated with this iterator
487
*/
488
@Override
489
void close();
490
}
491
```
492
493
### Exception Handling
494
495
Common exceptions in graph database operations.
496
497
```java { .api }
498
/**
499
* Thrown when a transaction operation fails
500
*/
501
public class TransactionFailureException extends RuntimeException {
502
public TransactionFailureException(String message, Throwable cause);
503
}
504
505
/**
506
* Thrown when attempting to access a non-existent entity
507
*/
508
public class NotFoundException extends RuntimeException {
509
public NotFoundException(String message);
510
}
511
512
/**
513
* Thrown when a deadlock is detected
514
*/
515
public class DeadlockDetectedException extends TransactionFailureException {
516
public DeadlockDetectedException(String message);
517
}
518
```