chocojunkie
chocojunkie

Reputation: 575

Finding cousin nodes in neo4j

I'm trying to get two specific blue nodes deriving from a common orange ancestor (image below). Here's a query I've tried that returns nothing:

MATCH (b1:Blue{...properties})<-[*2]-(:Orange{...})-[*2]->(b2:Blue{...}) RETURN (b1), (b2)

Nor does something like this work:

MATCH (b1:Blue{...})<-[*2]-(o:Orange{...}), (b2:Blue{...})<-[*2]-(o) RETURN (b1), b2)

The only way I can get the result I expect is with this clumsy query:

MATCH (b1:Blue{...}), (b2:Blue{...}), (r:Resource{...})
WHERE EXISTS ( (r)-[*2]->(p) ) AND EXISTS ( (r)-[*2]->(c) )
RETURN (b1), (b2)

Here is what the graph looks like:

enter image description here

Upvotes: 0

Views: 73

Answers (2)

jose_bacoy
jose_bacoy

Reputation: 12684

Is b1 and b2 always in pairs? if yes, then your first try query is almost correct. If b1, b2, b3,... are not in pairs (>2) then just return the collected nodes b2.

MATCH  (:Orange )-[*2]->(b2:Blue ) 
WITH collect(b2) as collected_blue 
RETURN collected_blue[0] as b1, collected_blue[1] as b2

Also, when you are going thru a path, you cannot repeat it. This why your first query is returning no result.

Upvotes: 1

nimrod serok
nimrod serok

Reputation: 16033

Edit:

MATCH (f:Brown)<-[:CONTAINS]-(:Orange)
WITH f
MATCH (b1:Blue)<-[:CONTAINS]-(f)-[:CONTAINS]->(b2:Blue)
RETURN b1,b2
LIMIT 1

This return the two Blue nodes on this data as b1 and b2:

MERGE (a:Orange {name: "A"})
MERGE (b:Brown {name: "B"})
MERGE (c:Brown {name: "C"})
MERGE (d:Blue {name: "D"})
MERGE (e:Blue {name: "E"})

MERGE (a)-[:CONTAINS]-(b)
MERGE (a)-[:CONTAINS]-(c)
MERGE (b)-[:FOLLOWS]-(c)
MERGE (c)-[:CONTAINS]-(d)
MERGE (c)-[:CONTAINS]-(e)
MERGE (d)-[:DEP]-(e)

Upvotes: 1

Related Questions