0
# Graph Operations
1
2
Comprehensive graph database functionality for managing vertices, edges, and graph traversals in ArangoDB. Supports named graphs with flexible edge definitions, graph collections, and specialized graph operations.
3
4
## Capabilities
5
6
### Graph Management
7
8
Create, delete, and manage named graphs with configurable edge definitions and vertex collections.
9
10
```python { .api }
11
class StandardDatabase:
12
def graph(self, name: str) -> Graph:
13
"""
14
Get graph interface.
15
16
Parameters:
17
- name: str, graph name
18
19
Returns:
20
Graph: Graph interface object
21
"""
22
23
def graphs(self) -> Result[List[Json]]:
24
"""
25
List all graphs.
26
27
Returns:
28
Result[List[Json]]: List of graph information dicts
29
"""
30
31
def create_graph(self, name: str, edge_definitions=None,
32
orphan_collections=None, **kwargs) -> Result[Graph]:
33
"""
34
Create a new graph.
35
36
Parameters:
37
- name: str, graph name
38
- edge_definitions: list, edge collection definitions
39
- orphan_collections: list, standalone vertex collections
40
- **kwargs: additional graph options
41
42
Returns:
43
Result[Graph]: Created graph object
44
"""
45
46
def delete_graph(self, name: str, ignore_missing: bool = False,
47
drop_collections=None) -> Result[bool]:
48
"""
49
Delete a graph.
50
51
Parameters:
52
- name: str, graph name
53
- ignore_missing: bool, ignore if graph doesn't exist
54
- drop_collections: bool, delete associated collections
55
56
Returns:
57
Result[bool]: True on success
58
"""
59
60
def has_graph(self, name: str) -> Result[bool]:
61
"""
62
Check if graph exists.
63
64
Parameters:
65
- name: str, graph name
66
67
Returns:
68
Result[bool]: True if graph exists
69
"""
70
```
71
72
### Graph Properties
73
74
Access graph configuration, edge definitions, and collection information.
75
76
```python { .api }
77
class Graph:
78
@property
79
def name(self) -> str:
80
"""Graph name."""
81
82
def properties(self) -> Result[Json]:
83
"""
84
Get graph properties.
85
86
Returns:
87
Result[Json]: Graph configuration dict
88
"""
89
```
90
91
### Vertex Collection Management
92
93
Manage vertex collections within graphs with creation, deletion, and listing operations.
94
95
```python { .api }
96
def vertex_collections(self) -> Result[List[str]]:
97
"""
98
List vertex collection names.
99
100
Returns:
101
Result[List[str]]: List of vertex collection names
102
"""
103
104
def has_vertex_collection(self, name: str) -> Result[bool]:
105
"""
106
Check if vertex collection exists in graph.
107
108
Parameters:
109
- name: str, collection name
110
111
Returns:
112
Result[bool]: True if collection exists in graph
113
"""
114
115
def vertex_collection(self, name: str) -> VertexCollection:
116
"""
117
Get vertex collection interface.
118
119
Parameters:
120
- name: str, collection name
121
122
Returns:
123
VertexCollection: Vertex collection object
124
"""
125
126
def create_vertex_collection(self, name: str, options=None) -> Result[VertexCollection]:
127
"""
128
Create vertex collection in graph.
129
130
Parameters:
131
- name: str, collection name
132
- options: dict, collection creation options
133
134
Returns:
135
Result[VertexCollection]: Created vertex collection
136
"""
137
138
def delete_vertex_collection(self, name: str, purge: bool = False) -> Result[bool]:
139
"""
140
Remove vertex collection from graph.
141
142
Parameters:
143
- name: str, collection name
144
- purge: bool, delete collection completely
145
146
Returns:
147
Result[bool]: True on success
148
"""
149
```
150
151
### Edge Definition Management
152
153
Define and manage edge collections with their vertex collection relationships.
154
155
```python { .api }
156
def edge_definitions(self) -> Result[List[Json]]:
157
"""
158
List edge definitions.
159
160
Returns:
161
Result[List[Json]]: List of edge definition dicts
162
"""
163
164
def has_edge_definition(self, name: str) -> Result[bool]:
165
"""
166
Check if edge definition exists.
167
168
Parameters:
169
- name: str, edge collection name
170
171
Returns:
172
Result[bool]: True if edge definition exists
173
"""
174
175
def has_edge_collection(self, name: str) -> Result[bool]:
176
"""
177
Check if edge collection exists in graph.
178
179
Parameters:
180
- name: str, collection name
181
182
Returns:
183
Result[bool]: True if collection exists
184
"""
185
186
def edge_collection(self, name: str) -> EdgeCollection:
187
"""
188
Get edge collection interface.
189
190
Parameters:
191
- name: str, collection name
192
193
Returns:
194
EdgeCollection: Edge collection object
195
"""
196
197
def create_edge_definition(self, edge_collection: str,
198
from_vertex_collections: Sequence[str],
199
to_vertex_collections: Sequence[str],
200
options=None) -> Result[EdgeCollection]:
201
"""
202
Create edge definition.
203
204
Parameters:
205
- edge_collection: str, edge collection name
206
- from_vertex_collections: list, source vertex collection names
207
- to_vertex_collections: list, target vertex collection names
208
- options: dict, edge collection options
209
210
Returns:
211
Result[EdgeCollection]: Created edge collection
212
"""
213
214
def replace_edge_definition(self, edge_collection: str,
215
from_vertex_collections: Sequence[str],
216
to_vertex_collections: Sequence[str],
217
sync=None, purge: bool = False) -> Result[EdgeCollection]:
218
"""
219
Replace edge definition.
220
221
Parameters:
222
- edge_collection: str, edge collection name
223
- from_vertex_collections: list, source vertex collection names
224
- to_vertex_collections: list, target vertex collection names
225
- sync: bool, wait for sync to disk
226
- purge: bool, purge orphaned edges
227
228
Returns:
229
Result[EdgeCollection]: Updated edge collection
230
"""
231
232
def delete_edge_definition(self, name: str, purge: bool = False,
233
sync=None) -> Result[bool]:
234
"""
235
Delete edge definition.
236
237
Parameters:
238
- name: str, edge collection name
239
- purge: bool, delete collection completely
240
- sync: bool, wait for sync to disk
241
242
Returns:
243
Result[bool]: True on success
244
"""
245
246
def edge_collections(self) -> Result[List[str]]:
247
"""
248
List edge collection names.
249
250
Returns:
251
Result[List[str]]: List of edge collection names
252
"""
253
```
254
255
### Vertex Operations
256
257
Direct vertex manipulation within graph context with validation of graph constraints.
258
259
```python { .api }
260
def has_vertex(self, vertex, rev=None, check_rev: bool = True) -> Result[bool]:
261
"""
262
Check if vertex exists.
263
264
Parameters:
265
- vertex: str or dict, vertex identifier
266
- rev: str, expected revision
267
- check_rev: bool, check revision matches
268
269
Returns:
270
Result[bool]: True if vertex exists
271
"""
272
273
def vertex(self, vertex, rev=None, check_rev: bool = True) -> Result:
274
"""
275
Get vertex document.
276
277
Parameters:
278
- vertex: str or dict, vertex identifier
279
- rev: str, expected revision
280
- check_rev: bool, check revision matches
281
282
Returns:
283
Result[Json]: Vertex document or None
284
"""
285
286
def insert_vertex(self, collection: str, vertex: Json, sync=None) -> Result[Json]:
287
"""
288
Insert vertex into graph.
289
290
Parameters:
291
- collection: str, vertex collection name
292
- vertex: dict, vertex document data
293
- sync: bool, wait for sync to disk
294
295
Returns:
296
Result[Json]: Vertex document metadata
297
"""
298
299
def update_vertex(self, vertex: Json, check_rev: bool = True,
300
keep_none: bool = True, sync=None) -> Result[Json]:
301
"""
302
Update vertex in graph.
303
304
Parameters:
305
- vertex: dict, vertex document with _key
306
- check_rev: bool, check current revision
307
- keep_none: bool, keep null values
308
- sync: bool, wait for sync to disk
309
310
Returns:
311
Result[Json]: Updated vertex metadata
312
"""
313
314
def replace_vertex(self, vertex: Json, check_rev: bool = True,
315
sync=None) -> Result[Json]:
316
"""
317
Replace vertex in graph.
318
319
Parameters:
320
- vertex: dict, complete replacement vertex
321
- check_rev: bool, check current revision
322
- sync: bool, wait for sync to disk
323
324
Returns:
325
Result[Json]: Replaced vertex metadata
326
"""
327
328
def delete_vertex(self, vertex, rev=None, check_rev: bool = True,
329
ignore_missing: bool = False, sync=None) -> Result:
330
"""
331
Delete vertex from graph.
332
333
Parameters:
334
- vertex: str or dict, vertex identifier
335
- rev: str, expected revision
336
- check_rev: bool, check revision matches
337
- ignore_missing: bool, ignore if vertex doesn't exist
338
- sync: bool, wait for sync to disk
339
340
Returns:
341
Result[Json|bool]: Deletion metadata or boolean
342
"""
343
```
344
345
### Edge Operations
346
347
Direct edge manipulation with automatic validation of vertex collection constraints.
348
349
```python { .api }
350
def has_edge(self, edge, rev=None, check_rev: bool = True) -> Result[bool]:
351
"""
352
Check if edge exists.
353
354
Parameters:
355
- edge: str or dict, edge identifier
356
- rev: str, expected revision
357
- check_rev: bool, check revision matches
358
359
Returns:
360
Result[bool]: True if edge exists
361
"""
362
363
def edge(self, edge, rev=None, check_rev: bool = True) -> Result:
364
"""
365
Get edge document.
366
367
Parameters:
368
- edge: str or dict, edge identifier
369
- rev: str, expected revision
370
- check_rev: bool, check revision matches
371
372
Returns:
373
Result[Json]: Edge document or None
374
"""
375
376
def insert_edge(self, collection: str, edge: Json, sync=None) -> Result[Json]:
377
"""
378
Insert edge into graph.
379
380
Parameters:
381
- collection: str, edge collection name
382
- edge: dict, edge document with _from and _to
383
- sync: bool, wait for sync to disk
384
385
Returns:
386
Result[Json]: Edge document metadata
387
"""
388
389
def update_edge(self, edge: Json, check_rev: bool = True,
390
keep_none: bool = True, sync=None) -> Result[Json]:
391
"""
392
Update edge in graph.
393
394
Parameters:
395
- edge: dict, edge document with _key
396
- check_rev: bool, check current revision
397
- keep_none: bool, keep null values
398
- sync: bool, wait for sync to disk
399
400
Returns:
401
Result[Json]: Updated edge metadata
402
"""
403
404
def replace_edge(self, edge: Json, check_rev: bool = True,
405
sync=None) -> Result[Json]:
406
"""
407
Replace edge in graph.
408
409
Parameters:
410
- edge: dict, complete replacement edge
411
- check_rev: bool, check current revision
412
- sync: bool, wait for sync to disk
413
414
Returns:
415
Result[Json]: Replaced edge metadata
416
"""
417
418
def delete_edge(self, edge, rev=None, check_rev: bool = True,
419
ignore_missing: bool = False, sync=None) -> Result:
420
"""
421
Delete edge from graph.
422
423
Parameters:
424
- edge: str or dict, edge identifier
425
- rev: str, expected revision
426
- check_rev: bool, check revision matches
427
- ignore_missing: bool, ignore if edge doesn't exist
428
- sync: bool, wait for sync to disk
429
430
Returns:
431
Result[Json|bool]: Deletion metadata or boolean
432
"""
433
```
434
435
### Graph Utilities
436
437
Convenience methods for common graph operations and traversals.
438
439
```python { .api }
440
def link(self, collection: str, from_vertex, to_vertex, data=None,
441
sync=None) -> Result[Json]:
442
"""
443
Create edge between two vertices.
444
445
Parameters:
446
- collection: str, edge collection name
447
- from_vertex: str or dict, source vertex
448
- to_vertex: str or dict, target vertex
449
- data: dict, additional edge data
450
- sync: bool, wait for sync to disk
451
452
Returns:
453
Result[Json]: Created edge metadata
454
"""
455
456
def edges(self, collection: str, vertex, direction=None) -> Result[Json]:
457
"""
458
Get edges connected to vertex.
459
460
Parameters:
461
- collection: str, edge collection name
462
- vertex: str or dict, vertex identifier
463
- direction: str, edge direction ('in', 'out', 'any')
464
465
Returns:
466
Result[Json]: Connected edges information
467
"""
468
469
def traverse(self, start_vertex, direction: str = "outbound",
470
item_order: str = "forward", strategy=None, **kwargs) -> Result[Json]:
471
"""
472
Traverse graph (deprecated - use AQL instead).
473
474
Parameters:
475
- start_vertex: str or dict, starting vertex
476
- direction: str, traversal direction
477
- item_order: str, result ordering
478
- strategy: str, traversal strategy
479
- **kwargs: additional traversal options
480
481
Returns:
482
Result[Json]: Traversal results
483
"""
484
```
485
486
## Usage Examples
487
488
### Basic Graph Setup
489
490
```python
491
from arango import ArangoClient
492
493
client = ArangoClient()
494
db = client.db('social', username='root', password='password')
495
496
# Create a social network graph
497
edge_definitions = [
498
{
499
'edge_collection': 'friendships',
500
'from_vertex_collections': ['users'],
501
'to_vertex_collections': ['users']
502
},
503
{
504
'edge_collection': 'follows',
505
'from_vertex_collections': ['users'],
506
'to_vertex_collections': ['users']
507
}
508
]
509
510
social_graph = db.create_graph(
511
'social_network',
512
edge_definitions=edge_definitions
513
)
514
515
print(f"Created graph: {social_graph.name}")
516
```
517
518
### Working with Vertices
519
520
```python
521
# Get vertex collection
522
users = social_graph.vertex_collection('users')
523
524
# Insert vertices
525
alice = users.insert({'name': 'Alice', 'age': 25, 'city': 'Boston'})
526
bob = users.insert({'name': 'Bob', 'age': 30, 'city': 'NYC'})
527
charlie = users.insert({'name': 'Charlie', 'age': 28, 'city': 'SF'})
528
529
print(f"Created users: {alice['_key']}, {bob['_key']}, {charlie['_key']}")
530
531
# Update vertex
532
users.update({
533
'_key': alice['_key'],
534
'occupation': 'Engineer'
535
})
536
537
# Get vertex
538
user_doc = social_graph.vertex(f"users/{alice['_key']}")
539
print(f"User: {user_doc['name']}, Age: {user_doc['age']}")
540
```
541
542
### Working with Edges
543
544
```python
545
# Get edge collection
546
friendships = social_graph.edge_collection('friendships')
547
follows = social_graph.edge_collection('follows')
548
549
# Create friendships (bidirectional)
550
friendship = friendships.insert({
551
'_from': f"users/{alice['_key']}",
552
'_to': f"users/{bob['_key']}",
553
'since': '2020-01-15',
554
'strength': 'close'
555
})
556
557
# Create follow relationships (directional)
558
follow1 = follows.insert({
559
'_from': f"users/{alice['_key']}",
560
'_to': f"users/{charlie['_key']}",
561
'since': '2021-03-10'
562
})
563
564
follow2 = follows.insert({
565
'_from': f"users/{bob['_key']}",
566
'_to': f"users/{charlie['_key']}",
567
'since': '2021-05-20'
568
})
569
570
# Using convenience link method
571
social_graph.link(
572
'friendships',
573
f"users/{bob['_key']}",
574
f"users/{charlie['_key']}",
575
data={'since': '2021-06-01', 'strength': 'casual'}
576
)
577
```
578
579
### Edge Definitions Management
580
581
```python
582
# List current edge definitions
583
definitions = social_graph.edge_definitions()
584
for definition in definitions:
585
print(f"Edge collection: {definition['collection']}")
586
print(f"From: {definition['from']}")
587
print(f"To: {definition['to']}")
588
589
# Add new edge definition
590
social_graph.create_edge_definition(
591
edge_collection='likes',
592
from_vertex_collections=['users'],
593
to_vertex_collections=['posts']
594
)
595
596
# Create the posts vertex collection
597
posts_collection = social_graph.create_vertex_collection('posts')
598
599
# Update edge definition
600
social_graph.replace_edge_definition(
601
edge_collection='follows',
602
from_vertex_collections=['users'],
603
to_vertex_collections=['users', 'pages'] # Now can follow pages too
604
)
605
```
606
607
### Graph Traversal with AQL
608
609
```python
610
# Find friends of friends
611
query = """
612
FOR user IN users
613
FILTER user.name == @start_user
614
FOR friend IN 1..1 OUTBOUND user friendships
615
FOR friend_of_friend IN 1..1 OUTBOUND friend friendships
616
FILTER friend_of_friend._key != user._key
617
RETURN DISTINCT {
618
name: friend_of_friend.name,
619
city: friend_of_friend.city,
620
mutual_friend: friend.name
621
}
622
"""
623
624
cursor = db.aql.execute(query, bind_vars={'start_user': 'Alice'})
625
friends_of_friends = list(cursor)
626
627
# Shortest path between users
628
shortest_path_query = """
629
FOR path IN OUTBOUND SHORTEST_PATH
630
@start_vertex TO @end_vertex
631
GRAPH @graph_name
632
RETURN path
633
"""
634
635
cursor = db.aql.execute(
636
shortest_path_query,
637
bind_vars={
638
'start_vertex': f"users/{alice['_key']}",
639
'end_vertex': f"users/{charlie['_key']}",
640
'graph_name': 'social_network'
641
}
642
)
643
644
path_result = cursor.next()
645
print(f"Shortest path length: {len(path_result['vertices'])}")
646
```
647
648
### Advanced Graph Operations
649
650
```python
651
# Get all edges connected to a vertex
652
connected_edges = social_graph.edges('friendships', f"users/{alice['_key']}")
653
print(f"Alice has {len(connected_edges['edges'])} friendship connections")
654
655
# Complex traversal with filters
656
complex_query = """
657
FOR user IN users
658
FILTER user.city == @city
659
FOR connection IN 1..3 ANY user GRAPH @graph_name
660
FILTER connection.age BETWEEN @min_age AND @max_age
661
COLLECT city = connection.city WITH COUNT INTO city_count
662
SORT city_count DESC
663
RETURN {
664
city: city,
665
count: city_count
666
}
667
"""
668
669
cursor = db.aql.execute(
670
complex_query,
671
bind_vars={
672
'city': 'Boston',
673
'graph_name': 'social_network',
674
'min_age': 20,
675
'max_age': 40
676
}
677
)
678
679
city_stats = list(cursor)
680
for stat in city_stats:
681
print(f"{stat['city']}: {stat['count']} connections")
682
```
683
684
### Graph Analytics
685
686
```python
687
# Centrality analysis
688
centrality_query = """
689
FOR user IN users
690
LET connections = (
691
FOR edge IN friendships
692
FILTER edge._from == user._id OR edge._to == user._id
693
RETURN 1
694
)
695
SORT LENGTH(connections) DESC
696
LIMIT 10
697
RETURN {
698
user: user.name,
699
degree: LENGTH(connections)
700
}
701
"""
702
703
top_connected = list(db.aql.execute(centrality_query))
704
print("Most connected users:")
705
for user in top_connected:
706
print(f"{user['user']}: {user['degree']} connections")
707
708
# Community detection (simple clustering)
709
community_query = """
710
FOR user IN users
711
LET friends = (
712
FOR friend IN 1..1 OUTBOUND user friendships
713
RETURN friend._key
714
)
715
LET mutual_connections = (
716
FOR friend_key IN friends
717
FOR mutual IN 1..1 OUTBOUND CONCAT('users/', friend_key) friendships
718
FILTER mutual._key IN friends
719
RETURN 1
720
)
721
RETURN {
722
user: user.name,
723
friends: LENGTH(friends),
724
clustering: LENGTH(friends) > 1 ? LENGTH(mutual_connections) / (LENGTH(friends) * (LENGTH(friends) - 1)) : 0
725
}
726
"""
727
728
clustering_results = list(db.aql.execute(community_query))
729
for result in clustering_results:
730
print(f"{result['user']}: clustering coefficient = {result['clustering']:.2f}")
731
```
732
733
### Graph Cleanup
734
735
```python
736
# Remove vertices (and connected edges automatically)
737
social_graph.delete_vertex(f"users/{charlie['_key']}")
738
739
# Remove edge definition
740
social_graph.delete_edge_definition('likes', purge=True)
741
742
# Remove vertex collection from graph
743
social_graph.delete_vertex_collection('posts', purge=True)
744
745
# Delete entire graph
746
db.delete_graph('social_network', drop_collections=False)
747
```