Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4j : Find children derived from same parents in cypher

Tags:

neo4j

cypher

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.

like image 560
tutysara Avatar asked Oct 17 '25 20:10

tutysara


1 Answers

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!
like image 55
ean5533 Avatar answered Oct 21 '25 00:10

ean5533



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!