Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypher query to find the longest path using neo4j 3.1.0 version

Tags:

neo4j

cypher

Can anybody send the Cypher query to find LONGEST PATH between two nodes using neo4j 3.1.0 version.

like image 736
raj Avatar asked Mar 11 '23 02:03

raj


1 Answers

The graph algorithm to find the longest path is not implemented.

Here is a Cypher query that gets all paths and sorts them by size:

// get the nodes
MATCH (a:Node), (b:Node)
WHERE ID(a) = 14 AND ID(b) = 7
WITH a,b
// match all paths
MATCH p=(a)-[*]-(b)
// return the longest
RETURN p, length(p) ORDER BY length(p) DESC LIMIT 1

However, without any restrictions on the query, this might not work on large graphs. Finding the longest path in an undirected graph is expensive: https://en.wikipedia.org/wiki/Longest_path_problem

And without restrictions on the query (direction and relationship type) the query will look for all undirected paths.

You should restrict your path query or try two solve your problem without the longest path.

like image 186
Martin Preusse Avatar answered May 03 '23 19:05

Martin Preusse