How Can we do this in cypher?
There are n parents p1, p2, p3.... pn and m children c1, c2,c3... cm.
Suppose c1 is derived from (child of) p1,p2 and p3 and also c2 is derived from (child of) p1, p2 and p3.
Given c1 can we find c2? (node derived from the same parents as c1)
A child can have 1...n parents.
Asked
Active
Viewed 1,496 times
4

tutysara
- 177
- 1
- 12
-
Do they need to have the EXACT same parents, or can it be an overlap? That is, if c1 derives from p1,p2,p3,and p4, and c2 derives from p1,p2,p3, do you want to find them? – ean5533 Mar 15 '13 at 19:21
-
We need to find the nodes derived from the exact same set of parents. – tutysara Mar 16 '13 at 06:42
1 Answers
8
I actually asked an extremely similar question here a few weeks ago, and the answer I got then will work for you too with just a bit of tweaking.
START c1=node(*), c2=node(*)
MATCH c1-[:ChildOf]->parent<-[:ChildOf]-c2
WITH c1, c2, count(parent) AS parentsFound
WHERE length(c1-[:ChildOf]->()) = parentsFound
AND length(c2-[:ChildOf]->()) = parentsFound
AND c1 <> c2
RETURN c1, c2
Note: presumably you will have a better way of picking your c1
and c2
than using node(*)
.
The logic of this query line by line:
- Starting with all children
c1
andc2
, - Find all
parent
s shared byc1
andc2
- Count the number of shared
parent
s that were found - Make sure that the number of
parent
s found matches the total number ofparent
s thatc1
has. - Make sure that the number of
parent
s found matches the total number ofparent
s thatc2
has. - (OPTIONAL) Don't bother comparing nodes to themselves
- Return the results!
-
1+1. I don't think you even need to do both where clauses--just checking the length of `c1-[:ChildOf]->()` should be sufficient, right? – Eve Freeman Mar 15 '13 at 19:56
-
1@WesFreeman Not necessarily. If c2 has MORE parents than just those shared with c1 then c2 won't be properly excluded without the second clause. If the OP doesn't care if c2 has more parents then that clause can be removed. – ean5533 Mar 15 '13 at 20:05