Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

neo4j - how to find all the longest paths with cypher query?

I want to write a cypher query which finds all the longest paths among nodes which have relationship with 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 1,2 and 3 length,not only the longest path,my query should find only the longest paths,I mean if there are 8 paths which suit to my first where condition ( where rel.status='on') ,with the length of 1,2,3,3,4,6,6,6 ,only the three paths with the length of 6 should be returned.

what shoud I do?

please guide me,I am new to neo4j,and tried a lot but have not got anything except dizziness,I will be so thankful for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try moving up your relationship property criterion to the first path match, or you'll be calculating the max length on paths that are not filtered with that criterion. Then carry the paths and the max length into the second leg of the query so you don't have to match all the paths again. You can collect the paths to carry them in the WITH clause, and then filter on path length when you return. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...