4

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.

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 Answers1

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:

  1. Starting with all children c1 and c2,
  2. Find all parents shared by c1 and c2
  3. Count the number of shared parents that were found
  4. Make sure that the number of parents found matches the total number of parents that c1 has.
  5. Make sure that the number of parents found matches the total number of parents that c2 has.
  6. (OPTIONAL) Don't bother comparing nodes to themselves
  7. Return the results!
Community
  • 1
  • 1
ean5533
  • 8,884
  • 3
  • 40
  • 64
  • 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