From 5875cd5b4422157b38571b361b1b6ddfff3727c9 Mon Sep 17 00:00:00 2001 From: Dave MacLeod <56599343+Dhghomon@users.noreply.github.com> Date: Thu, 12 Dec 2024 14:19:13 +0900 Subject: [PATCH] Add extra example of parentheses in graph queries (#1045) --- .../doc-surrealql/statements/relate.mdx | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/src/content/doc-surrealql/statements/relate.mdx b/src/content/doc-surrealql/statements/relate.mdx index 1545d0f17..4fa27512b 100644 --- a/src/content/doc-surrealql/statements/relate.mdx +++ b/src/content/doc-surrealql/statements/relate.mdx @@ -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: