Skip to content

Commit

Permalink
Add extra example of parentheses in graph queries (#1045)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dhghomon authored Dec 12, 2024
1 parent b676259 commit 5875cd5
Showing 1 changed file with 81 additions and 0 deletions.
81 changes: 81 additions & 0 deletions src/content/doc-surrealql/statements/relate.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,87 @@ SELECT
FROM person:tobie;
```

Parentheses can be used at each point of a graph query. The example below includes `person` records (authors) connected to `book` records by the `wrote` table. As both the `person` and `book` tables have fields that can be useful when filtering, they can be isolated with parentheses at this point of the graph query in order to filter using the `WHERE` clause.

```surql
CREATE person:j_r_r_tolkien SET
name = "J.R.R. Tolkien",
born = d'1891-01-03';
-- Very approximate date of birth
CREATE person:plato SET
name = "Plato",
born = "-0428-06-01";
CREATE book:fotr SET
name = "The Fellowship of the Ring";
CREATE book:republic SET
name = "The Republic",
original_name = "Πολιτεία";
RELATE person:j_r_r_tolkien->wrote->book:fotr SET written_at = "North Oxford";
RELATE person:plato->wrote->book:republic SET written_at = "Athens";
SELECT
name,
-- Isolate 'wrote' to use WHERE
->(wrote WHERE written_at = "Athens")->book.* AS books_written_in_athens
FROM person;
SELECT
name,
-- Isolate 'book' to use WHERE
->wrote->(book WHERE "Ring" IN name).* AS books_about_rings
FROM person;
```

```surql title="Output"
-------- Query --------
[
{
books_written_in_athens: [],
name: 'J.R.R. Tolkien'
},
{
books_written_in_athens: [
{
id: book:republic,
name: 'The Republic',
original_name: 'Πολιτεία'
}
],
name: 'Plato'
}
]
-------- Query --------
[
{
books_about_rings: [
{
id: book:fotr,
name: 'The Fellowship of the Ring'
}
],
name: 'J.R.R. Tolkien'
},
{
books_about_rings: [],
name: 'Plato'
}
]
```

As of SurrealDB 2.0, [destructuring](/docs/surrealql/datamodel/idioms#destructuring) can also be used to pick and choose which fields to access inside a graph query. The following query will return the same output as above, except that `original_name: 'Πολιτεία'` will no longer show up.

```surql
SELECT
name,
->(wrote WHERE written_at = "Athens")->book.{ name, id } AS books_written_in_athens
FROM person;
```

### Bidirectional relation querying

All of the queries up to now have been clear about what sort of record is found at the `in` and `out` fields: `in` is the record that is doing something, while `out` is the record that has something done to it:
Expand Down

0 comments on commit 5875cd5

Please sign in to comment.