简体   繁体   中英

Neo4J Cypher - finding meeting point of two paths

This is more of a "how to" question, there can be different ways but trying to find the most performant and effective way of solving this requirement.

I have a graph where there are nodes that act as fork nodes ie they spawn into two paths and these paths later meet at some other node, I know the node id and properties of the fork node (Node A in example below) and would like to know the node (Node B in ex below) at which the two paths meet.

Note - these paths can be of variable length ie one may have 6 nodes and the other only 2 nodes for eg

NodeA -[]-> Node 1 -[]-> Node 2 -[]-> Node 3 -[]-> Node 4 -[]-> Node 5 -[]-> Node 6 -[]-> Node B -[]-> Node C -[]-> Node D -[]-> Node E
NodeA -[]-> Node 7 -[]-> Node 8 -[]-> Node B -[]-> Node C -[]-> Node D -[]-> Node E

So if you see Node A spawns into two paths which finally meet again at Node B, so I want to get the Node B knowing Node A, pls suggest how we can do this in Cypher.

Thanks, Deepesh

I'm going to assume that you know node a via it's id property and that it's 1234 . Also you may want to use labels here. I'm not sure if you're using them or not, so I left them out.

MATCH
  (a)-[*1..10]->(b),
  (a)-[*1..10]->(b)
WHERE a.id = 1234
RETURN b

You could return the lengths of the paths too, but this should get you the result. Also note that you can adjust the max length of the path ( 10 in this example) as a tradeoff on the performance of the query (it depends on the structure of your graph)

EDIT:

Also, if that doesn't work you may need to do:

MATCH
  path1 = (a)-[*1..10]->(b),
  path2 = (a)-[*1..10]->(b)
WHERE a.id = 1234 AND path1 <> path2
RETURN b

The answer to my question is as below (thanks to Brian - updating his answer with a LIMIT 1)

MATCH
path1 = (a)-[*1..10]->(b),
path2 = (a)-[*1..10]->(b)
WHERE a.id = 1234 AND path1 <> path2
RETURN b LIMIT 1

Adding LIMIT 1 to return only the intersection node otherwise it returns all the nodes following the intersection node also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM