Database Reference
In-Depth Information
to visit, so you move to the nodes on the next depth level, starting with the descendants
of node 2, visiting nodes 5 and 6, in that order. Then you continue to nodes 7 and 8, and
finally you visit the descendant of node 4 (node 9). The order of nodes you visited using
the breadth-first algorithm is as follows:
1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9
In breadth-first traversal, you visit nodes closer to the root node earlier, leaving nodes fur-
ther away from the root node for later.
Let's now update the traversal implementation to use the breadth-first strategy. The tra-
versal description builder in the Neo4j Traversal API has a dedicated method to do just
that, as the following listing illustrates.
Listing 8.2. Breadth-first traversal using the Neo4j Traversal API
As you can see, the code is very similar. The only difference is that you use a different
method to specify the traversal ordering when building a traversal description
. The
console output will match the order established earlier in this section:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 ->
8.1.3. Comparing depth-first and breadth-first ordering
As you've seen in the last two sections, a depth-first traversal will favor searches with the
solution in the left part of the graph. A breadth-first traversal will be faster when the result
is closer to the starting node than if it's a longer distance from the starting node. These two
characteristics are very important when designing the graph and the traversal you need to
execute.
Search WWH ::




Custom Search