Traversal Framework

This section provides an overview of the Traversal Framework, a detailed description of the Neo4j Traversal Framework Java API and how to use it.

The Neo4j Traversal Framework Java API is a callback-based, lazily-executed way of specifying desired movements through a graph in Java. Some traversal examples can be found on Traversal.

Although the Traversal Framework is less readable and more complex than the Cypher query language, it offers a powerful approach to traversing the graph. This is because the Traversal Framework has the ability to dynamically make custom choices at each step of the traversal, thus making the process more expressive and potentially more performant than Cypher.

It is generally recommended to use Cypher wherever it is possible. However, when using the Traversal Framework, keep in mind:

  • Cypher uses memory tracking which allows a query to be aborted if it occupies too much memory. However, when mixing Cypher with Java in the Traversal API (e.g. on a function), you may run out of memory.

  • Do not reuse objects fetched during a Traversal in another transaction. Instead, use their IDs to fetch new ones.

When to use the Traversal Framework over Cypher

Some of the advantages of using the Traversal Framework over Cypher include:

  • The Traversal Framework allows the use of any desired Java library to help in the evaluation of the traversal.

  • It allows customized pruning during the traversal of a path. This could potentially improve the performance of a traversal. See Evaluator for more information.

  • With Cypher, it is not possible to specify the order in which paths are expanded (e.g. depth-first). However, with the Traversal Framework it is possible to specify the order of paths traversed.

  • With Cypher, relationships are only traversed once (RELATIONSHIP_GLOBAL uniqueness). By using the Traversal Framework, it is possible to specify the uniqueness constraints of the path traversed.

Main concepts

A traversal takes a start node on a graph and returns a set of Path representing the visited nodes and their relationships. Traversals are defined by a traversal description, which may contain the following elements:

graphdb traversal description
  • Starting node — defines where the traversal begins.

  • Pathexpander — defines what to traverse, typically in terms of relationship direction and type.

  • Uniqueness — defines the restrictions of previously traversed nodes and relationships on the graph.

  • Evaluator — decides what to return and whether to stop or continue the traversal beyond its current position.

  • Order — defines in which order paths are expanded, for example depth-first or breadth-first.

Using the Traversal Framework

The Traversal Framework can be used embedded in Java applications. It can also be used when extending Neo4j with a User-defined Procedure. See an example here.

To read more about the traversals, see: