App db
What it shows
The example creates an in-memory database (DbMemory) with a root node aliased users, inserts users as plain key-value nodes without any schema and links them to the root with edges. It then finds a user with a depth-first search filtered by username - the graph equivalent of SELECT * FROM users WHERE username = "user1" - and prints the id and the key-value pairs of the found element from the raw QueryResult.
Run it
cargo run -p agdb --example app_db
Inserting schemaless data
Each node gets its own list of key-value pairs. There is no schema, so the second user can simply omit the age. The result of the insert is passed directly to the next query to connect the new nodes to the users root:
// Inserts the raw data by providing list of keys and values
// for each node. Notice we can easily create sparse data
// omitting certain fields as there is no schema to enforce.
let users = db.exec_mut(
QueryBuilder::insert()
.nodes()
.values([
vec![
("username", "user1").into(),
("password", "password123").into(),
("age", 20).into(),
],
vec![
("username", "user2").into(),
("password", "password456").into(),
],
])
.query(),
)?;
// Link the users with the "users" node. Note that we are referring to
// the users node with an alias "users" we have given it and to
// the new user nodes by supplying the result of the previous query directly.
// One could also use the `QueryResult::ids()` method to extract the ids.
db.exec_mut(
QueryBuilder::insert()
.edges()
.from("users")
.to(users)
.query(),
)?;
Searching and reading the result
The search starts at users and returns only elements whose username is user1. The result always has the same shape: a numeric result and a list of elements, each with an id and its key-value pairs. Nodes have positive ids and edges negative ids:
let user_result = db.exec(
QueryBuilder::select()
.search()
.depth_first()
.from("users")
.where_()
.key("username")
.value("user1")
.query(),
)?;
if user_result.result == 1 {
println!("User: {:?}", user_result.elements[0].id);
for key_value in user_result.elements[0].values.iter() {
println!(" {}: {}", key_value.key, key_value.value);
}
}
Learn more
- Concepts - graph, ids and data types.
- Queries reference - insert, search and conditions.
- User types - the same data with Rust structs instead of raw key-values.