Search code examples
graphneo4jcypherdepth-first-searchbreadth-first-search

Guarantees on the evaluation order of recursive relationship match in Cyher/Neo4j


For a match like MATCH (node0 {id: 1})-[:REL*]->(nodeN),

are there any guarantees on:

  • match being Depth-First / Breath-First?
  • match branching from one node through one relation or another?

Experimenting on this, for the same data set (created from integration tests with entities created in the same order each time), two Neo4j instances (one in docker ran through github action, another on docker desktop) seems to have:

  • the same Depth-First semantics
  • different branching order

branching

Is there any Cypher parameters to influence 1) DFS vs. BFS behaviour 2) order of traversal from one node i.e. based on a relation property

I know there are traversal (i.e. tree-spanning) algorithms that do a similar thing but I don't want to explore them yet for the reason they are more restrictive in regard to property filtering (being able to filter only by labels)


Solution

  • I don't think there are any parameters right to do any of these things.

    1. DFS vs BFS -> Path matching is DFS only. For the query MATCH (node0 {id: 1})-[:REL*]->(nodeN), first cypher will obtain a nodeN, at one hop distance. Then it will traverse from that node and go forward. A good way to notice this is by looking at the output of the following query:

      MATCH (n{id: 1})-[r:REL*]->(nodeN) return n, nodeN, r

    2. We can't influence the traversal order using some property. There is no such keyword, the WHERE clause will filter out the results, and ORDER BY will order the final results, but nothing right now can influence the traversals internally.