Neo4j trouble excluding complete subgraphs

51 views Asked by At

I'm very new to graph databases and neo4j/cypher. I can load info from a csv file and make some basic cypher sentences, but I'm having a hard time understanding how to exclude subtrees from my result tree. Below is an image of an example of my graph, it is a simple parent-child tree.

First Tree

The problem comes when I want to apply a business rule: when you find a child node where the level is greater or equals than his father, then the child must be excluded and all his descendants too, all the relations and nodes of the subtree must not be part of the final result.

I tried with:

match (p:Person {id:"A" })<-[r:CHILD_OF*]-(c:Person)
where c.level < p.level
return c,p;

But unfortunately I'm getting undesired nodes and relations because I can not traverse and exclude the complete subtrees with its branches:

With my query

What I'm trying to achieve is this:

Result expected

Any help would be greatly appreciated.

2

There are 2 answers

0
jose_bacoy On BEST ANSWER

I will collect all children with levels more than their parents then check the ALL of these child do not have a child or children in the result.

MATCH (p:Person {name:"A" })<-[ :CHILD_OF*]-(c:Person)
WHERE c.level >= p.level
WITH p,  collect(c) as allChildren 
MATCH (p)<-[ :CHILD_OF*]-(child:Person) 
WHERE child.level < p.level AND ALL(c in allChildren WHERE NOT EXISTS( (c)<-[:CHILD_OF*]-(child)))
RETURN p, child

enter image description here

2
Charchit Kapoor On

Try this:

MATCH (p:Person {id:"A" })<-[r:CHILD_OF*]-(c:Person)
WHERE c.level >= p.level
WITH p, c
MATCH (p)<-[r:CHILD_OF*]-(child:Person) 
WHERE child.level < p.level AND NOT (c)<-[:CHILD_OF*]-(child)
RETURN p, child

In this query, we first fetch all the child nodes whose level is greater or equal to that of the parent. Then, we fetch the children whose level is less than that of the parent and which are not children of the nodes whose level is greater than or equal to that of the parent.