Examples
Joins
agdb example: combining data from nodes and edges without a join operator
What it shows
agdb has no join operator because the relations are stored directly as edges. The example models a user who has access to several databases, with the database name stored on the nodes and the user's role stored on the edges, and shows two ways to read both into one list of UserDb { name, role }.
Run it
cargo run -p agdb --example joins
Single search
A depth-first search from the user returns edges and nodes in order: each edge (with role) is followed by the node it points to (with name). The sign of the id tells them apart - edges have negative ids:
let mut user_dbs: Vec<UserDb> = vec![];
db.exec(
QueryBuilder::select()
.search()
.depth_first()
.from("user")
.where_()
.keys("role")
.or()
.keys("name")
.query(),
)?
.elements
.into_iter()
.for_each(|e| {
if e.id.0 < 0 {
// handle the edge
user_dbs.push(UserDb {
role: e.values[0].value.to_string(),
name: String::new(),
});
} else {
// handle the node
user_dbs.last_mut().unwrap().name = e.values[0].value.to_string();
}
});
Multiple queries in a transaction
When the data is sparse, or you need more control, run several queries inside one read transaction. All of them see the same consistent state of the database:
let user_dbs = db.transaction(|t| -> Result<Vec<UserDb>, DbError> {
let db_names = t.exec(
QueryBuilder::select()
.search()
.from("user")
.where_()
.neighbor()
.and()
.keys("name")
.query(),
)?;
let mut dbs = vec![];
for db_name in db_names.elements {
let role = t.exec(
QueryBuilder::select()
.search()
.to(db_name.id)
.limit(1)
.where_()
.keys("role")
.query(),
)?;
dbs.push(UserDb {
name: db_name.values[0].value.to_string(),
role: role.elements[0].values[0].value.to_string(),
});
}
Ok(dbs)
})?;
Learn more
- Transactions in the queries reference.
- Conditions -
keys,neighbor,and/orand more. - Search - search directions,
limitand ordering.