Graph traversal is a search technique used to systematically visit and explore all the nodes in a graph. Its primary goal is to reveal and examine the structure and connections of the graph. There are two common strategies for graph traversal:
The DFS algorithm is based on the principle of backtracking and proceeds as follows:
Below is an example of traversing the graph using the DFS approach, starting from node A and assuming to visit neighbors in alphabetical order (A~Z):


GQLINSERT (A:default {_id: "A"}), (B:default {_id: "B"}), (C:default {_id: "C"}), (D:default {_id: "D"}), (E:default {_id: "E"}), (F:default {_id: "F"}), (G:default {_id: "G"}), (A)-[:default]->(B), (A)-[:default]->(D), (B)-[:default]->(E), (C)-[:default]->(A), (E)-[:default]->(F), (F)-[:default]->(C), (G)-[:default]->(D)
| Name | Type | Default | Description |
|---|---|---|---|
startNode | STRING | / | Required. Starting node _id. |
maxDepth | INT | -1 | Maximum depth to traverse (-1 = unlimited). |
direction | STRING | out | Edge direction: in, out, or both. |
Returns:
| Column | Type | Description |
|---|---|---|
nodeId | STRING | Node identifier (_id) |
depth | INT | Depth from start node |
parent | STRING | Parent node in DFS tree |
discoveryOrder | INT | Order in which the node was first visited |
finishOrder | INT | Order in which the node was fully explored |
GQLCALL algo.dfs({ startNode: "B", direction: "in" }) YIELD nodeId, depth, parent, discoveryOrder, finishOrder
Result:
| nodeId | depth | parent | discoveryOrder | finishOrder |
|---|---|---|---|---|
| B | 0 | 0 | 9 | |
| A | 1 | B | 1 | 8 |
| C | 2 | A | 2 | 7 |
| F | 3 | C | 3 | 6 |
| E | 4 | F | 4 | 5 |
Returns the same columns as run mode, streamed for memory efficiency.
GQLCALL algo.dfs.stream({ startNode: "A", maxDepth: 3 }) YIELD nodeId, depth RETURN nodeId, depth
Result:
| nodeId | depth |
|---|---|
| A | 0 |
| D | 1 |
| B | 1 |
| E | 2 |
| F | 3 |
Returns:
| Column | Type | Description |
|---|---|---|
nodeCount | INT | Total number of nodes visited |
maxDepth | INT | Maximum depth reached from start node |
GQLCALL algo.dfs.stats({ startNode: "A" }) YIELD nodeCount, maxDepth
Result:
| nodeCount | maxDepth |
|---|---|
| 6 | 4 |