Skip to content

Commit

Permalink
Add example of graph edges existing before records exist (#1071)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dhghomon authored Dec 19, 2024
1 parent 3fe9e29 commit e2b3ed8
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions src/content/doc-surrealql/statements/relate.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,69 @@ SELECT * FROM likes;
]
```


### Using RELATE on non-existent records

As mentioned at the top of the page, `RELATE` can be used for records that do not yet exist. While this behaviour can be overridden by using the `ENFORCED` keyword, it can be useful in certain situations.

For example, the `VALUE` clause inside a [`DEFINE FIELD`](/docs/surrealdb/surrealql/statements/define/field) statement is calculated every time a record is altered (that is, every time it is created or updated). If this value depends on a graph edge, creating the record first will cause `VALUE` to calculate it based on a nonexistent path.

In the following example, a `house` table has a field called `has_road_access` that depends on whether any `->has_road` paths return an output that is not empty. Meanwhile, the city has a new road under construction but no houses are present and their details have not been set yet.

```surql
-- Returns true if $this->has_road path is not empty
DEFINE FIELD has_road_access ON TABLE house VALUE !!$this->has_road->road;
CREATE road SET name = "Dalhurst Way", length = 10.5;
```

As the addresses of the upcoming houses have been decided, the `->has_road` path can be set ahead of time by giving the `house` records an ID based on their exact address.

```surql
LET $road = SELECT * FROM ONLY road WHERE name = "Dalhurst Way" LIMIT 1;
RELATE [
house:[218, "Dalhurst Way"],
house:[222, "Dalhurst Way"],
house:[226, "Dalhurst Way"],
]->has_road->$road;
```

Later on, two new houses are completed in the city and registered in the database. As the path to `house:[218, "Dalhurst Way"]` has already been set up, the `has_road_access` field will evaluate to `true`, while the other house in the middle of nowhere will evaluate to `false`.

```surql
CREATE house:[218, "Dalhurst Way"] SET floors = 2, bedrooms = 5;
CREATE house:[0, "Middle of nowhere"] SET floors = 4, bedrooms = 12;
```

```surql
-------- Query --------
[
{
bedrooms: 5,
floors: 2,
has_road_access: true,
id: house:[
218,
'Dalhurst Way'
]
}
]
-------- Query --------
[
{
bedrooms: 12,
floors: 4,
has_road_access: false,
id: house:[
0,
'Middle of nowhere'
]
}
]
```

## Querying graphs

### Different ways to reach similar results
Expand Down

0 comments on commit e2b3ed8

Please sign in to comment.