Article DetailsDetailsHelp Details Cypher is optimized for finding the shortest path between two nodes using the shortestPath() function. It does not have a function for longest path. To find the longest path use the queries below. Root to leaf in a tree For tree structured data, use this query to find the longest path between a root node and leaf node. This query will work even if you don't know how many connections there are in between. MATCH p=(parent:Root)-[:HAS_CHILD*1..10]->(child:Node) WHERE NOT (child)-[:HAS_CHILD]->() RETURN p What the above query is doing: The variable length 1..10 will find all paths (there should be only one), 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). Longest path when there are multiple paths present For data not in a tree structure there may be several paths between nodes. Find the longest path by ordering by path length and only taking the longest path: MATCH p=(start:Node)-[:REL*1..10]->(end:Node) WHERE id(start) = 123 AND id(end) = 456 RETURN p ORDER BY length(p) DESC LIMIT 1 Tips for making these queries more efficient With a fairly well connected graph, variable-length path queries like this may get increasingly expensive. Here are some tips to keep these performant. Constrain relationship type and direction - If possible, use only the relevant types needed, and use a directed relationship. This may cut down on the paths followed during expansion.Supply an upper bound for the variable-length pattern - Patterns without bounds may get out of hand in a well connected graph. Setting an upper bound can help constrain the work the query needs to perform.Use all() or none() in the WHERE clause following the MATCH - If predicates need to be evaluated during expansion, and they must apply to all nodes or relationships in the path, use all() or none() on the nodes or relationships from the path to evaluate during expansion rather than filtering after all paths are found.Use APOC path expanders for special cases or restrictions - For certain restrictions, such as not repeating nodes during expansion, you may want to use path expander procs from APOC Procedures to enforce different configurations of uniqueness during expansion. InformationTitleAchieving longestPath Using CypherArticle Created Date3/15/2024, 10:56 PMURL Name115003805027-Achieving-longestPath-Using-CypherLast Modified Date9/18/2026, 6:08 PM