While Cypher is optimized for finding the shortest path between two nodes, with such functionality as shortestPath()
,
it does not have the same sort of function for longest path. In some cases, you may want this, and not the shortest route.
For example, if you wanted to do the longest path between a parent entity and a child (leaf node), and you don't know how many
there are in between:
MATCH p=(parent:Entity)-[r:HAS_CHILD*1..10]->(child:Person)
RETURN p;
The problem with this is that it will give you all paths, one for each hop, until you get to the leaf node. What you want is just
the longest path to see how the parent and leaf child are connected. To do this efficiently, do the following:
MATCH p=(parent:Entity)-[r:HAS_CHILD*1..10]->(child:Person)
WHERE size( (child)-[r:HAS_CHILD]->() ) = 0
RETURN p;
What the above query is doing: The variable length 1..10 will find all paths, including the longestPath, for any Parent-Child path that spans at most 10 hops. The WHERE clause is needed to filter the paths to only those where the leaf child nodes have no outgoing :HAS_CHILD relationships (i.e. it finds the end of the chain).