# 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