How to find all the longest paths with a cypher request?

I want to write a cypher query that finds all the longest paths between nodes that have a relationship with the STATUS = "on" property with each other, this is what I have done so far:

start n=node(*) match p = n-[r:INCLUDE*..]->m with n,MAX(length(p)) as l match p = n-[r:INCLUDE*..]->m WHERE all(rel in r where rel.status='on' AND (length(p) = l) ) return p,l 

It returns 3 paths with lengths 1,2 and 3, and not only the longest path, my query should find only the longest paths, I mean if there are 8 paths that match my first, where is the condition ( where rel.status='on' ), with a length of 1,2,3,3,4,6,6,6, only three paths with a length of 6 should be returned.

What am I doing?

Please call me, I am new to neo4j and have tried a lot, but I have nothing but dizziness, I will be so grateful for your help.

+6
source share
1 answer

Try moving your relationship property criterion to match the first path, or you will calculate the maximum length along paths that are not filtered using this criterion. Then transfer the paths and the maximum length to the second part of the request so that you do not have to match all the paths again. You can collect paths to wrap them in a WITH clause, and then filter the path length when returning. Try something like

 START n=node(*) MATCH p=n-[rels:INCLUDE*]->m WHERE ALL (rel IN rels WHERE rel.status='on') WITH COLLECT(p) AS paths, MAX(length(p)) AS maxLength RETURN FILTER(path IN paths WHERE length(path)= maxLength) AS longestPaths 
+12
source

Source: https://habr.com/ru/post/957326/


All Articles