Guides

Data modelling

How to model application data as an agdb graph: nodes, edges, values, aliases, indexes, typed data and schema evolution

This guide is a bridge between the concepts (what a graph in agdb is) and the worked examples such as Efficient agdb (a whole application built step by step). It answers a single question: given my application data, what should the graph look like?

Building blocks

  • Nodes are entities. A user, a post, a database, an invoice.
  • Edges are relationships. They are directed (from -> to) and, like nodes, can carry values. A role, a created timestamp or a liked flag on an edge is often all the "join table" you need.
  • Values are key-value properties of nodes and edges, e.g. ("username", "alice").
  • Labels are keys without a value (DbValue::None). They tag an element cheaply (4 bytes) and can be matched with keys("admin").
  • Aliases are names for nodes. A node with an alias can be used in place of its id in any query.
// Aliased roots, a user node with a label and a value.
db.exec_mut(
    QueryBuilder::insert()
        .nodes()
        .aliases(["users", "posts"])
        .query(),
)?;

let alice = db.exec_mut(
    QueryBuilder::insert()
        .nodes()
        .values([[("username", "alice").into(), ("admin", DbValue::None).into()]])
        .query(),
)?;

// The edge from the root is the "row belongs to table" relationship.
db.exec_mut(
    QueryBuilder::insert()
        .edges()
        .from("users")
        .to(&alice)
        .query(),
)?;

Roots and edges instead of tables

There are no tables in agdb. The role of a table is played by a root node with an alias (users, posts) and the rows are the nodes hanging off it. Which nodes belong to the "table" is expressed by edges rather than by a schema, so one node can belong to several collections at once (e.g. alice can be reachable from users, from admins and from the team she is in) without duplicating anything. The aliased root is also the entry point of every search: you start there and walk towards the data.

Relationalagdb
tableroot node with an alias + child nodes connected from it
rownode with values
columnkey of a value (rows need not all have the same keys)
foreign key (one-to-many)an edge from the parent to the child
join table (many-to-many)edges between the two nodes, with values on the edge (role, since)
UNIQUE / indexinsert().index("key") plus a check inside a mutable transaction
WHEREsearch conditions (where_()) or an index lookup
JOINfollowing edges in a search (see Joins)

For the reasoning behind this see Why not SQL? and Why object queries?.

One-to-many

The edge from the parent is the relationship. A post authored by a user is simply an edge user -> post; "all posts of alice" is a search from alice.

db.exec_mut(
    QueryBuilder::insert()
        .edges()
        .from(&alice)
        .to(&post)
        .query(),
)?;

let posts = db.exec(
    QueryBuilder::select()
        .values(["title"])
        .search()
        .from(alice.elements[0].id)
        .where_()
        .neighbor()
        .query(),
)?;

Many-to-many with values on the edge

No join table is needed. The edge between the two nodes is the row of the join table and it holds the attributes of the relationship. This is taken from the Joins example, where user is the alias of a user node and dbs the result of inserting two database nodes:

db.exec_mut(
    QueryBuilder::insert()
        .edges()
        .from("user")
        .to(dbs)
        .values([[("role", "admin").into()], [("role", "read").into()]])
        .query(),
)?;

Use values_uniform when every edge gets the same values (e.g. ("liked", 1)). Reading the data back is a graph search, not a join: see the Joins example for both the single-pass depth-first approach and the transaction based one.

There are two ways to find an element and the model should be chosen with that in mind.

Graph search starts at an alias and follows edges while checking conditions. Its cost depends on how much of the graph it has to visit, so a good model narrows the search by structure: users -> alice -> posts visits only alice's posts. Limit the traversal with conditions:

// The users root and its direct children, without walking through archived nodes.
QueryBuilder::select()
    .values(["username"])
    .search()
    .from("users")
    .where_()
    .distance_less_than_or_equal(2)
    .and()
    .not_beyond()
    .keys("archived")
    .query();
  • distance_* conditions bound how far the search goes (1 = first edge, 2 = the node behind it).
  • beyond() / not_beyond() decide whether the search continues through the elements that match (see Queries).
  • When you only want one item use depth_first() with limit(1); the default breadth first search is better suited for "closest first" results.

Index lookup finds elements by the value of a key regardless of where they are. It pays off when the data is uniform and cannot be split sensibly by structure, typically a lookup by username, email or session token among many thousands of siblings.

db.exec_mut(QueryBuilder::insert().index("username").query())?;

let user = db.exec(
    QueryBuilder::select()
        .values(["username"])
        .search()
        .index("username")
        .value("alice")
        .query(),
)?;

An index can be created at any time, existing elements are indexed too. Keep in mind that:

  • an index is on a key and covers every element having it (nodes and edges alike), so pick keys that are specific to one kind of entity;
  • the index is not a constraint. A UNIQUE equivalent is a search inside a mutable transaction that rejects the insert if the value exists, as done in Efficient agdb and the Indexes example;
  • index searches skip the traversal, so the traversal conditions (distance, neighbor, beyond, not_beyond) are not available in them.

A rule of thumb: model the relationships that you traverse (owner, parent, membership) as edges and index the keys you look up from the outside (login names, tokens, external ids).

Typed data

Hand-writing key-value pairs gets tedious. Derive DbType on your structs to insert and select them directly; the derive macros are described in the derive macros reference and the User types example.

#[derive(Debug, DbType)]
struct User {
    username: String,
    password: String,
}

let user = User { username: "alice".into(), password: "secret".into() };
let id = db.exec_mut(QueryBuilder::insert().element(&user).query())?.elements[0].id;

let user: User = db
    .exec(
        QueryBuilder::select()
            .values(User::db_keys())
            .ids(id)
            .query(),
    )?
    .try_into()?;

DbType only maps fields to keys, so two structs with the same fields are indistinguishable in the graph. When several such types hang off the same node derive DbElement instead: it additionally stores the type name with each element (the db_element_id value) and lets you select only the elements of one type with select().elements::<T>() or filter them with where_().element::<T>(). Only use it where types really overlap, because it stores one more value per element.

Evolving the model

The model is not fixed up front. Properties can be added to existing elements, new edges and roots introduced and indexes created later, all with ordinary queries run in a transaction. Typical changes are caching a computed value on a node (a likes counter instead of counting edges every time) or introducing an intermediate node. See Schema updates for a walk-through and the Schema migration example for converting stored values between two versions of a type.

Common pitfalls

  • Everything under one root. An alias with millions of direct children is fine for index lookups but a search from it that has to scan the children is not. If you traverse from a root, split it by something meaningful (per user, per tenant, per year) so searches start closer to the data.
  • Large blobs. Values over 15 bytes are stored out of line and every key-value pair costs at least 20 bytes (see storage). Keep big files outside of the database and store a reference (path, URL, object key) instead.
  • Reused ids. A removed element frees its db id and a later insert may receive the same one. Never keep a bare id as a long-lived external reference to something that can be deleted; use a value of your own (a uuid, a username) with an index. See concepts.
  • Long mutable transactions. Only one mutable transaction runs at a time. Do the minimum inside it (check, insert, connect) and prepare the data beforehand. Keep reads that do not need to be atomic with the write outside the closure.
  • Searching without bounds. A search without conditions walks the whole reachable graph. Add distance, limit or a not_beyond condition, or start from a node closer to the data.