Rust API Reference
This content is for v0.9.2. Switch to the latest version for up-to-date documentation.
Version: 0.4.4
Crate: graphqlite
Connection
Section titled “Connection”Low-level connection type wrapping rusqlite::Connection with Cypher support.
Constructors
Section titled “Constructors”Connection::open<P: AsRef<Path>>(path: P) -> Result<Connection>Connection::open_in_memory() -> Result<Connection>Connection::from_rusqlite(conn: rusqlite::Connection) -> Result<Connection>Connection::open_with_extension<P: AsRef<Path>>(path: P, ext_path: &str) -> Result<Connection>| Method | Description |
|---|---|
open |
Open or create a database at path |
open_in_memory |
Open an in-memory database |
from_rusqlite |
Wrap an existing rusqlite::Connection; loads the extension into it |
open_with_extension |
Open database and load extension from explicit path |
Methods
Section titled “Methods”Connection::cypher
Section titled “Connection::cypher”fn cypher(&self, query: &str) -> Result<CypherResult>Execute a Cypher query with no parameters.
Connection::cypher_with_params
Section titled “Connection::cypher_with_params”Deprecated since 0.4.0. Use
cypher_builder()instead.
fn cypher_with_params(&self, query: &str, params: &serde_json::Value) -> Result<CypherResult>Execute a Cypher query with parameters. params must be a JSON object; keys correspond to $name placeholders.
Connection::cypher_rows_each
Section titled “Connection::cypher_rows_each”fn cypher_rows_each<F>(&self, query: &str, params: Option<&serde_json::Value>, f: F) -> Result<()>where F: FnMut(&Row) -> Result<()>Stream a Cypher query’s rows through the cypher_rows virtual table. f
receives each Row as SQLite steps the result, so peak memory is one row;
returning an error from f stops the scan and propagates. A write query
without RETURN yields one row of modification counts.
conn.cypher_rows_each("MATCH (n:Person) RETURN n.name AS name", None, |row| { let name: String = row.get("name")?; println!("{name}"); Ok(())})?;Connection::validate
Section titled “Connection::validate”fn validate(&self, query: &str) -> Result<ValidationResult>Validate a Cypher query without executing it. The query goes through the
scanner, the grammar and the same compile-time semantic pass cypher() runs
before transform; the graph is never read or written, so validating a
CREATE creates nothing. Errors that only surface during transform or
execution (an unknown variable, for example) are not detected.
The outcome is data, not an Err: ValidationResult { valid, diagnostic },
where diagnostic is a Diagnostic { code, message, line, column } with
code PARSE_ERROR (scanner or grammar; line and column are the 1-based
location of the offending token) or VALIDATION_ERROR (static semantic
violation such as RETURN NOT 1; no location).
let v = conn.validate("MATCH (n:Person RETURN n.name")?;if let Some(d) = v.diagnostic { println!("{}", d); // PARSE_ERROR at 1:17: Line 1, Col 17: syntax error, unexpected RETURN, expecting ')'}Connection::cypher_builder
Section titled “Connection::cypher_builder”fn cypher_builder(&self, query: &str) -> CypherQueryReturn a CypherQuery builder for chaining parameter additions before execution.
Connection::execute
Section titled “Connection::execute”fn execute(&self, sql: &str) -> Result<usize>Execute raw SQL. Returns the number of rows changed.
Connection::sqlite_connection
Section titled “Connection::sqlite_connection”fn sqlite_connection(&self) -> &rusqlite::ConnectionBorrow the underlying rusqlite::Connection.
CypherQuery
Section titled “CypherQuery”Builder returned by Connection::cypher_builder.
cypher_query .param("name", "Alice") .param("age", 30) .run() -> Result<CypherResult>CypherResult
Section titled “CypherResult”Represents the rows returned by a Cypher query.
Methods
Section titled “Methods”| Method | Signature | Description |
|---|---|---|
len |
fn len(&self) -> usize |
Number of rows |
is_empty |
fn is_empty(&self) -> bool |
True if zero rows |
columns |
fn columns(&self) -> &[String] |
Ordered column names |
| Index | result[i] |
Returns &Row at index i |
| Iterate | for row in &result |
Iterates &Row |
A single result row.
Row::get
Section titled “Row::get”fn get<T: FromSql>(&self, column: &str) -> Result<T>Get a column value by name. T must implement FromSql.
Supported types for T
| Rust type | Cypher type |
|---|---|
String |
String, converted from any scalar |
i64 |
Integer |
f64 |
Float |
bool |
Boolean |
Option<String> |
String or null |
Option<i64> |
Integer or null |
Option<f64> |
Float or null |
Option<bool> |
Boolean or null |
Example
let name: String = row.get("n.name")?;let age: Option<i64> = row.get("n.age")?;High-level graph API mirroring the Python Graph.
Constructors
Section titled “Constructors”Graph::open(path: &str) -> Result<Graph>Graph::open_in_memory() -> Result<Graph>Node Operations
Section titled “Node Operations”fn upsert_node(&self, node_id: &str, props: &serde_json::Value, label: &str) -> Result<i64>fn get_node(&self, id: &str) -> Result<Option<serde_json::Value>>fn has_node(&self, id: &str) -> Result<bool>fn delete_node(&self, id: &str) -> Result<()>fn get_all_nodes(&self, label: Option<&str>) -> Result<Vec<serde_json::Value>>Edge Operations
Section titled “Edge Operations”fn upsert_edge(&self, source: &str, target: &str, props: &serde_json::Value, rel_type: &str) -> Result<i64>fn get_edge(&self, src: &str, dst: &str, rel_type: Option<&str>) -> Result<Option<serde_json::Value>>fn has_edge(&self, src: &str, dst: &str, rel_type: Option<&str>) -> Result<bool>fn delete_edge(&self, src: &str, dst: &str, rel_type: Option<&str>) -> Result<()>fn get_all_edges(&self) -> Result<Vec<serde_json::Value>>fn query(&self, cypher: &str, params: Option<&serde_json::Value>) -> Result<Vec<serde_json::Value>>fn validate(&self, cypher: &str) -> Result<ValidationResult> // see Connection::validatefn stats(&self) -> Result<serde_json::Value>fn node_degree(&self, id: &str) -> Result<i64>fn get_neighbors(&self, id: &str) -> Result<Vec<serde_json::Value>>fn get_node_edges(&self, id: &str) -> Result<Vec<serde_json::Value>>fn get_edges_from(&self, id: &str) -> Result<Vec<serde_json::Value>>fn get_edges_to(&self, id: &str) -> Result<Vec<serde_json::Value>>fn get_edges_by_type(&self, id: &str, rel_type: &str) -> Result<Vec<serde_json::Value>>Graph Cache
Section titled “Graph Cache”fn load_graph(&self) -> Result<serde_json::Value>fn unload_graph(&self) -> Result<serde_json::Value>fn reload_graph(&self) -> Result<serde_json::Value>fn graph_loaded(&self) -> Result<bool>Graph Algorithms
Section titled “Graph Algorithms”All return Result<Vec<T>> where T is a typed result struct. See Graph Algorithms for parameter defaults.
| Method | Signature | Returns |
|---|---|---|
| PageRank | fn pagerank(&self, damping: f64, iterations: usize) -> Result<Vec<PageRankResult>> |
PageRankResult |
| Degree centrality | fn degree_centrality(&self) -> Result<Vec<DegreeCentralityResult>> |
DegreeCentralityResult |
| Betweenness | fn betweenness_centrality(&self) -> Result<Vec<BetweennessCentralityResult>> |
BetweennessCentralityResult |
| Closeness | fn closeness_centrality(&self) -> Result<Vec<ClosenessCentralityResult>> |
ClosenessCentralityResult |
| Eigenvector | fn eigenvector_centrality(&self, iterations: usize) -> Result<Vec<EigenvectorCentralityResult>> |
EigenvectorCentralityResult |
| Community (label prop) | fn community_detection(&self, iterations: usize) -> Result<Vec<CommunityResult>> |
CommunityResult |
| Louvain | fn louvain(&self, resolution: f64) -> Result<Vec<CommunityResult>> |
CommunityResult |
| WCC | fn weakly_connected_components(&self) -> Result<Vec<ComponentResult>> |
ComponentResult |
| SCC | fn strongly_connected_components(&self) -> Result<Vec<ComponentResult>> |
ComponentResult |
| Shortest path | fn shortest_path(&self, source: &str, target: &str, weight_property: Option<&str>) -> Result<ShortestPathResult> |
ShortestPathResult |
| A* | fn astar(&self, source: &str, target: &str, lat_prop: Option<&str>, lon_prop: Option<&str>) -> Result<AStarResult> |
AStarResult |
| APSP | fn all_pairs_shortest_path(&self) -> Result<Vec<ApspResult>> |
ApspResult |
| BFS | fn bfs(&self, start: &str, max_depth: i64) -> Result<Vec<TraversalResult>> |
TraversalResult |
| DFS | fn dfs(&self, start: &str, max_depth: i64) -> Result<Vec<TraversalResult>> |
TraversalResult |
| Node similarity | fn node_similarity(&self, node1_id: Option<i64>, node2_id: Option<i64>, threshold: f64, top_k: usize) -> Result<Vec<NodeSimilarityResult>> |
NodeSimilarityResult |
| KNN | fn knn(&self, node_id: i64, k: usize) -> Result<Vec<KnnResult>> |
KnnResult |
| Triangle count | fn triangle_count(&self) -> Result<Vec<TriangleCountResult>> |
TriangleCountResult |
GraphManager
Section titled “GraphManager”Manages named graphs stored as SQLite files in a directory.
Constructor
Section titled “Constructor”GraphManager::open(path: &str) -> Result<GraphManager>Methods
Section titled “Methods”fn list(&self) -> Result<Vec<String>>fn exists(&self, name: &str) -> boolfn create(&self, name: &str) -> Result<Graph>fn open(&self, name: &str) -> Result<Graph>fn open_or_create(&self, name: &str) -> Result<Graph>fn drop(&self, name: &str) -> Result<()>fn query(&mut self, cypher: &str, graph_names: &[&str]) -> Result<CypherResult>fn query_sql(&mut self, sql: &str, graph_names: &[&str]) -> Result<Vec<Vec<rusqlite::types::Value>>>fn close(self) -> Result<()>graph_names must list every graph referenced by a FROM clause (or by table prefix in query_sql); an empty slice returns Error::InvalidArgument. Graph names must be identifiers (^[A-Za-z_][A-Za-z0-9_]*$); anything else returns Error::InvalidGraphName.
Result Types
Section titled “Result Types”All are plain structs deriving Debug, Clone, serde::Serialize, serde::Deserialize.
ValidationResult / Diagnostic
Section titled “ValidationResult / Diagnostic”pub struct ValidationResult { pub valid: bool, pub diagnostic: Option<Diagnostic>, // None when valid}
pub struct Diagnostic { pub code: String, // "PARSE_ERROR" | "VALIDATION_ERROR" pub message: String, pub line: Option<u32>, // 1-based, parse errors only pub column: Option<u32>, // 1-based, parse errors only}Returned by Connection::validate and Graph::validate. Diagnostic
implements Display (PARSE_ERROR at 1:17: ...). These two derive Debug,
Clone, PartialEq, Eq rather than serde traits.
PageRankResult
Section titled “PageRankResult”pub struct PageRankResult { pub node_id: i64, pub user_id: String, pub score: f64,}DegreeCentralityResult
Section titled “DegreeCentralityResult”pub struct DegreeCentralityResult { pub node_id: i64, pub user_id: String, pub in_degree: usize, pub out_degree: usize, pub degree: usize,}BetweennessCentralityResult
Section titled “BetweennessCentralityResult”pub struct BetweennessCentralityResult { pub node_id: i64, pub user_id: String, pub score: f64,}ClosenessCentralityResult
Section titled “ClosenessCentralityResult”pub struct ClosenessCentralityResult { pub node_id: i64, pub user_id: String, pub score: f64,}EigenvectorCentralityResult
Section titled “EigenvectorCentralityResult”pub struct EigenvectorCentralityResult { pub node_id: i64, pub user_id: String, pub score: f64,}CommunityResult
Section titled “CommunityResult”pub struct CommunityResult { pub node_id: i64, pub user_id: String, pub community: i64,}ComponentResult
Section titled “ComponentResult”pub struct ComponentResult { pub node_id: i64, pub user_id: String, pub component: i64,}ShortestPathResult
Section titled “ShortestPathResult”pub struct ShortestPathResult { pub path: Vec<String>, pub distance: f64, pub found: bool,}AStarResult
Section titled “AStarResult”pub struct AStarResult { pub path: Vec<String>, pub distance: f64, pub found: bool, pub nodes_explored: usize,}ApspResult
Section titled “ApspResult”pub struct ApspResult { pub source: String, pub target: String, pub distance: f64,}TraversalResult
Section titled “TraversalResult”pub struct TraversalResult { pub user_id: String, pub depth: usize, pub order: usize,}NodeSimilarityResult
Section titled “NodeSimilarityResult”pub struct NodeSimilarityResult { pub node1: String, pub node2: String, pub similarity: f64,}KnnResult
Section titled “KnnResult”pub struct KnnResult { pub neighbor: String, pub similarity: f64, pub rank: usize,}TriangleCountResult
Section titled “TriangleCountResult”pub struct TriangleCountResult { pub node_id: i64, pub user_id: String, pub triangles: usize, pub clustering_coefficient: f64,}Error Enum
Section titled “Error Enum”pub enum Error { Sqlite(rusqlite::Error), Json(serde_json::Error), Cypher(String), ExtensionNotFound(String), TypeError(String), ColumnNotFound(String), GraphError(String),}| Variant | Cause |
|---|---|
Sqlite |
SQLite or rusqlite error |
Json |
JSON serialization/deserialization failure |
Cypher |
The extension rejected a query (parse, validation or execution). Raised by cypher(), the query builder, cypher_rows_each() and GraphManager::query; the string is the extension’s error message |
ExtensionNotFound |
Could not locate the extension library |
TypeError |
Type mismatch when reading a column value |
ColumnNotFound |
Column name not present in result |
GraphError |
General graph operation failure |
Error implements std::error::Error and std::fmt::Display.
Example
Section titled “Example”use graphqlite::{Connection, Graph};
fn main() -> graphqlite::Result<()> { let conn = Connection::open_in_memory()?;
conn.cypher("CREATE (:Person {name: 'Alice', age: 30})")?; conn.cypher("CREATE (:Person {name: 'Bob', age: 25})")?; conn.cypher("MATCH (a:Person {name:'Alice'}), (b:Person {name:'Bob'}) CREATE (a)-[:KNOWS]->(b)")?;
let result = conn.cypher("MATCH (n:Person) RETURN n.name, n.age ORDER BY n.age")?; for row in &result { let name: String = row.get("n.name")?; let age: i64 = row.get("n.age")?; println!("{} is {}", name, age); }
let graph = Graph::open_in_memory()?; graph.upsert_node("alice", &serde_json::json!({"age": 30}), "Person")?; let scores = graph.pagerank(0.85, 20)?; for r in &scores { println!("{}: {:.4}", r.user_id, r.score); }
Ok(())}