graph_d 1.3.2

A native graph database implementation in Rust with built-in JSON support and SQLite-like simplicity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# Graph_D API Reference

Complete API documentation for the Graph_D native graph database.

## Table of Contents

- [Core Types]#core-types
- [Graph Operations]#graph-operations
- [Query Engine]#query-engine
- [Transaction Management]#transaction-management
- [Storage Layer]#storage-layer
- [Error Handling]#error-handling

## Core Types

### `Graph`

The main graph database structure.

```rust
pub struct Graph {
    pub storage: Storage,
    // private fields...
}
```

#### Methods

##### `Graph::new() -> Result<Self>`
Creates a new in-memory graph database.

```rust
let mut graph = Graph::new()?;
```

##### `Graph::open<P: AsRef<Path>>(path: P) -> Result<Self>`
Opens a persistent graph database at the specified path.

```rust
let mut graph = Graph::open("my_database.db")?;
```

##### `Graph::create_node(properties: HashMap<String, Value>) -> Result<Id>`
Creates a new node with the given properties.

```rust
let node_id = graph.create_node([
    ("name".to_string(), json!("Alice")),
    ("age".to_string(), json!(30)),
].into())?;
```

##### `Graph::get_node(id: Id) -> Result<Option<Node>>`
Retrieves a node by its ID.

```rust
if let Some(node) = graph.get_node(node_id)? {
    println!("Node: {:?}", node);
}
```

##### `Graph::create_relationship(from_id: Id, to_id: Id, rel_type: String, properties: HashMap<String, Value>) -> Result<Id>`
Creates a relationship between two nodes.

```rust
let rel_id = graph.create_relationship(
    alice_id,
    bob_id,
    "KNOWS".to_string(),
    [("since".to_string(), json!("2020"))].into(),
)?;
```

##### `Graph::get_relationship(id: Id) -> Result<Option<Relationship>>`
Retrieves a relationship by its ID.

```rust
if let Some(rel) = graph.get_relationship(rel_id)? {
    println!("Relationship: {} -> {}", rel.from_id, rel.to_id);
}
```

##### `Graph::get_relationships_for_node(node_id: Id) -> Result<Vec<Relationship>>`
Gets all relationships for a given node.

```rust
let relationships = graph.get_relationships_for_node(alice_id)?;
```

### `Node`

Represents a node in the graph.

```rust
pub struct Node {
    pub id: Id,
    pub properties: HashMap<String, Value>,
}
```

#### Methods

##### `Node::new(id: Id, properties: HashMap<String, Value>) -> Self`
Creates a new node.

##### `Node::get_property(&self, key: &str) -> Option<&Value>`
Gets a property value by key.

```rust
if let Some(name) = node.get_property("name") {
    println!("Name: {}", name);
}
```

##### `Node::set_property(&mut self, key: String, value: Value)`
Sets a property value.

##### `Node::has_property(&self, key: &str) -> bool`
Checks if a property exists.

##### `Node::property_keys(&self) -> Vec<&String>`
Gets all property keys.

### `Relationship`

Represents a relationship in the graph.

```rust
pub struct Relationship {
    pub id: Id,
    pub from_id: Id,
    pub to_id: Id,
    pub rel_type: String,
    pub properties: HashMap<String, Value>,
}
```

#### Methods

##### `Relationship::new(id: Id, from_id: Id, to_id: Id, rel_type: String, properties: HashMap<String, Value>) -> Self`
Creates a new relationship.

##### Property methods (same as Node)
- `get_property()`, `set_property()`, `has_property()`, `property_keys()`

##### `Relationship::connects(&self, node1_id: Id, node2_id: Id) -> bool`
Checks if this relationship connects the given nodes.

##### `Relationship::is_outgoing_from(&self, node_id: Id) -> bool`
Checks if this relationship is outgoing from the given node.

##### `Relationship::is_incoming_to(&self, node_id: Id) -> bool`
Checks if this relationship is incoming to the given node.

## Query Engine

### `QueryBuilder`

Fluent API for graph queries.

```rust
pub struct QueryBuilder<'a> {
    // private fields...
}
```

#### Construction

##### `QueryBuilder::new(graph: &Graph, start_nodes: Vec<Id>) -> Self`
Creates a query starting from multiple nodes.

##### `QueryBuilder::from_node(graph: &Graph, node_id: Id) -> Self`
Creates a query starting from a single node.

```rust
let query = QueryBuilder::from_node(&graph, alice_id);
```

#### Traversal Methods

##### `outgoing(self, rel_type: &str) -> Result<Self>`
Traverses outgoing relationships of the given type.

```rust
let friends = QueryBuilder::from_node(&graph, alice_id)
    .outgoing("FRIENDS_WITH")?
    .nodes()?;
```

##### `incoming(self, rel_type: &str) -> Result<Self>`
Traverses incoming relationships.

##### `either(self, rel_type: &str) -> Result<Self>`
Traverses relationships in either direction.

#### Filtering Methods

##### `filter_by_property(self, key: &str, value: &Value) -> Result<Self>`
Filters nodes by property value.

```rust
let engineers = QueryBuilder::new(&graph, all_employees)
    .filter_by_property("department", &json!("Engineering"))?
    .nodes()?;
```

#### Aggregation Methods

##### `aggregate(&self, function: AggregateFunction) -> Result<AggregateResult>`
Applies an aggregation function.

```rust
let count = query.aggregate(AggregateFunction::Count)?;
let avg_salary = query.aggregate(AggregateFunction::Avg("salary".to_string()))?;
```

#### Sorting Methods

##### `sort(self, criteria: Vec<SortCriteria>) -> Result<Self>`
Sorts results by given criteria.

```rust
let sorted = query.sort(vec![
    SortCriteria::desc("salary"),
    SortCriteria::asc("name"),
])?;
```

##### `sorted_page(&self, criteria: Vec<SortCriteria>, pagination: Pagination) -> Result<SortedPage<Node>>`
Gets sorted and paginated results.

#### Result Methods

##### `node_ids(&self) -> &[Id]`
Gets the current node IDs.

##### `nodes(&self) -> Result<Vec<Node>>`
Gets the current nodes.

##### `count(&self) -> usize`
Counts the current results.

##### `is_empty(&self) -> bool`
Checks if results are empty.

### Aggregation Functions

```rust
pub enum AggregateFunction {
    Count,
    Sum(String),         // property key
    Avg(String),         // property key
    Min(String),         // property key
    Max(String),         // property key
    Distinct(String),    // property key
    GroupBy(String),     // property key
}
```

### Sort Criteria

```rust
pub struct SortCriteria {
    pub property: String,
    pub direction: SortDirection,
}

pub enum SortDirection {
    Asc,
    Desc,
}
```

#### Methods

##### `SortCriteria::asc(property: impl Into<String>) -> Self`
Creates ascending sort criteria.

##### `SortCriteria::desc(property: impl Into<String>) -> Self`
Creates descending sort criteria.

### Pagination

```rust
pub struct Pagination {
    pub offset: usize,
    pub limit: usize,
}
```

#### Methods

##### `Pagination::new(offset: usize, limit: usize) -> Self`
Creates new pagination parameters.

### Path Finding

```rust
pub struct PathFinder<'a> {
    // private fields...
}
```

#### Methods

##### `PathFinder::new(graph: &Graph) -> Self`
Creates a new path finder.

##### `shortest_path(&self, from_id: Id, to_id: Id) -> Result<Option<Vec<Id>>>`
Finds the shortest path between two nodes using BFS.

```rust
let path_finder = PathFinder::new(&graph);
if let Some(path) = path_finder.shortest_path(alice_id, bob_id)? {
    println!("Path: {:?}", path);
}
```

## Transaction Management

### `TransactionManager`

Manages concurrent transactions.

```rust
pub struct TransactionManager {
    // private fields...
}
```

#### Methods

##### `TransactionManager::new(default_isolation_level: IsolationLevel) -> Self`
Creates a new transaction manager.

```rust
let tx_manager = TransactionManager::new(IsolationLevel::ReadCommitted);
```

##### `begin(&self) -> Transaction`
Begins a new transaction with default isolation level.

##### `begin_concurrent(&self) -> ConcurrentTransaction`
Begins a new concurrent transaction with locking support.

```rust
let mut tx = tx_manager.begin_concurrent();
```

##### `lock_statistics(&self) -> LockStatistics`
Gets current lock statistics.

### `ConcurrentTransaction`

A transaction with concurrency control.

#### Methods

##### `read_lock(&mut self, resource: LockableResource) -> Result<()>`
Acquires a read lock on a resource.

```rust
tx.read_lock(LockableResource::Node(1))?;
```

##### `write_lock(&mut self, resource: LockableResource) -> Result<()>`
Acquires a write lock on a resource.

```rust
tx.write_lock(LockableResource::Node(2))?;
```

##### `commit(self) -> Result<()>`
Commits the transaction and releases all locks.

##### `rollback(self) -> Result<()>`
Rolls back the transaction and releases all locks.

### Isolation Levels

```rust
pub enum IsolationLevel {
    ReadUncommitted,
    ReadCommitted,
    RepeatableRead,
    Serializable,
}
```

### Lockable Resources

```rust
pub enum LockableResource {
    Node(Id),
    Relationship(Id),
    Schema,
}
```

## Storage Layer

### `Storage`

Storage backend abstraction.

#### Methods

##### `Storage::new() -> Result<Self>`
Creates new in-memory storage.

##### `Storage::open<P: AsRef<Path>>(path: P) -> Result<Self>`
Opens persistent storage.

##### `flush(&self) -> Result<()>`
Flushes pending writes to disk.

## Error Handling

### `GraphError`

Main error type for the database.

```rust
pub enum GraphError {
    Storage(String),
    NotFound(String),
    Invalid(String),
    Serialization(String),
    Transaction(String),
    Concurrency(String),
    Io(String),
}
```

### `Result<T>`

Type alias for `std::result::Result<T, GraphError>`.

```rust
pub type Result<T> = std::result::Result<T, GraphError>;
```

## Examples

### Basic Usage

```rust
use graph_d::{Graph, Result};
use serde_json::json;

fn main() -> Result<()> {
    let mut graph = Graph::new()?;
    
    let alice_id = graph.create_node([
        ("name".to_string(), json!("Alice")),
    ].into())?;
    
    let bob_id = graph.create_node([
        ("name".to_string(), json!("Bob")),
    ].into())?;
    
    let _rel_id = graph.create_relationship(
        alice_id,
        bob_id,
        "KNOWS".to_string(),
        std::collections::HashMap::new(),
    )?;
    
    Ok(())
}
```

### Query Example

```rust
use graph_d::query::{QueryBuilder, AggregateFunction, SortCriteria};

// Find and sort high-value customers
let valuable_customers = QueryBuilder::new(&graph, all_customers)
    .filter_by_property("total_purchases", &json!(1000))?
    .sort(vec![SortCriteria::desc("total_purchases")])?
    .nodes()?;

// Calculate average order value
let avg_order = QueryBuilder::new(&graph, all_orders)
    .aggregate(AggregateFunction::Avg("amount".to_string()))?;
```

### Transaction Example

```rust
use graph_d::transaction::{TransactionManager, IsolationLevel, LockableResource};

let tx_manager = TransactionManager::new(IsolationLevel::ReadCommitted);
let mut tx = tx_manager.begin_concurrent();

tx.write_lock(LockableResource::Node(1))?;
// Perform operations...
tx.commit()?;
```

## Performance Tips

1. **Use appropriate isolation levels** - ReadCommitted is usually sufficient
2. **Batch operations** - Create multiple nodes/relationships in sequence
3. **Use pagination** - For large result sets
4. **Index frequently queried properties** - Via the query system
5. **Minimize lock scope** - Hold locks for the shortest time possible
6. **Use read locks when possible** - They don't block other readers