# 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](/docs/guides/concepts) (what a graph in `agdb` is) and the worked examples such as [Efficient agdb](/docs/references/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.

```rs
// 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.

<table>
<thead>
  <tr>
    <th>
      Relational
    </th>
    
    <th>
      <code>
        agdb
      </code>
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      table
    </td>
    
    <td>
      root node with an alias + child nodes connected from it
    </td>
  </tr>
  
  <tr>
    <td>
      row
    </td>
    
    <td>
      node with values
    </td>
  </tr>
  
  <tr>
    <td>
      column
    </td>
    
    <td>
      key of a value (rows need not all have the same keys)
    </td>
  </tr>
  
  <tr>
    <td>
      foreign key (one-to-many)
    </td>
    
    <td>
      an edge from the parent to the child
    </td>
  </tr>
  
  <tr>
    <td>
      join table (many-to-many)
    </td>
    
    <td>
      edges between the two nodes, with values on the edge (<code>
        role
      </code>
      
      , <code>
        since
      </code>
      
      )
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        UNIQUE
      </code>
      
       / index
    </td>
    
    <td>
      <code>
        insert().index("key")
      </code>
      
       plus a check inside a mutable transaction
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        WHERE
      </code>
    </td>
    
    <td>
      search conditions (<code>
        where_()
      </code>
      
      ) or an index lookup
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        JOIN
      </code>
    </td>
    
    <td>
      following edges in a search (see <a href="/docs/examples/joins">
        Joins
      </a>
      
      )
    </td>
  </tr>
</tbody>
</table>

For the reasoning behind this see [Why not SQL?](/blog/why-not-sql) and [Why object queries?](/blog/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.

```rs
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](/docs/examples/joins) example, where `user` is the alias of a user node and `dbs` the result of inserting two database nodes:

```rs
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](/docs/examples/joins) example for both the single-pass depth-first approach and the transaction based one.

## Index or graph search?

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:

```rs
// 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](/docs/references/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.

```rs
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](/docs/references/efficient-agdb) and the [Indexes](/docs/examples/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](/docs/references/derive-macros) and the [User types](/docs/examples/user-types) example.

```rs
#[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](/docs/references/efficient-agdb#schema-updates) for a walk-through and the [Schema migration](/docs/examples/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](/docs/guides/concepts#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](/docs/guides/concepts#graph).
- **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.
