• Start

Graph

Recursive traversals

Use SurrealQL recursive path syntax and idioms to walk a graph to a chosen depth and return nested structures along a relationship.

Recursive queries let you follow a path to a specific depth without spelling out every hop.

person records linked by child_of:

CREATE |person:1..16|;
-- parents of person:1
RELATE person:1->child_of->[person:2, person:3];
-- grandparents of person:1
RELATE person:2->child_of->[person:4, person:5];
RELATE person:3->child_of->[person:6, person:7];
-- great-grandparents of person:1
RELATE person:4->child_of->[person:8, person:9];
RELATE person:5->child_of->[person:10, person:11];
RELATE person:6->child_of->[person:12, person:13];
RELATE person:7->child_of->[person:14, person:15];

You can repeat the path manually:

SELECT 
->child_of->person AS parents,
->child_of->person->child_of->person AS grandparents,
->child_of->person->child_of->person->child_of->person AS great_grandparents
FROM ONLY person:1;

Or use recursive path repetition:

SELECT 
@.{1}->child_of->person AS parents,
@.{2}->child_of->person AS grandparents,
@.{3}->child_of->person AS great_grandparents
FROM ONLY person:1;

Recursive syntax is not only shorthand: it can return a single nested object that repeats down a path:

-- Range to start at a depth of one, try to go down to depth of three
SELECT @.{3}.{
id,
-- At each depth, use this path to reach the next one
parents: ->child_of->person.@
} FROM person:1;

Starting from a record id:

person:1.{3}.{
id,
parents: ->child_of->person.@
};

Recursive paths are defined in idioms and apply beyond graph-only use cases.

Was this page helpful?