Jon
Jon

Reputation: 10473

Find nodes based on parent relationships in neo4j

Problem

I have a neo4j graph database with data that looks like the following:

enter image description here

Item A is missing in Category 1 and Item B is missing in Category 2. Category 2 is a child of Category 1.

When an item is missing in a category, it's also missing in all child categories.

Question

How do you query neo4 for all items missing in Category 2 including those items missing in parent categories? Bear in mind that Category 1 itself could also have a parent with missing items, which should also be included. A Category can only have one or zero parents.

What I've tried

I tried using the following cypher query but it doesn't work. I think this is because the variable relationship is on the MISSING_IN relationship, but it should really be on the CHILD_OF relationship.

MATCH (Category {name:2})<-[r:MISSING_IN*]-(Item) RETURN Item

Upvotes: 2

Views: 1114

Answers (3)

Govind Singh
Govind Singh

Reputation: 15490

try the below cypher

MATCH path=(c:Category{name:2})-[:CHILD_OF*]->(i:Category)
WITH [x in nodes(path) | id(x)] AS nodeIds
MATCH (n1:Category)<-[:MISSING_IN]-(p)
WHERE id(n1) in nodeIds
RETURN p

Upvotes: 1

Christophe Willemsen
Christophe Willemsen

Reputation: 20175

The following query do the trick and will also handle the case when Category 2 does not have any parent and is also validated by the console link provided by @logisima

MATCH (c:Category {name:2})-[:CHILD_OF*0..]->(parent:Category)<-[:MISSING_IN]-(i:Item)
RETURN c.name, collect(i) as items

Upvotes: 1

logisima
logisima

Reputation: 7458

If you have a root category node, this query should work :

MATCH 
  path=shortestPath((cat2:Category {name:'2'})-[:CHILD_OF*]->(catRoot:Category {name:'0'} )),
  (n)<-[:MISSING_IN]-(item:Item)
WHERE
  n IN nodes(path)
RETURN item

Upvotes: 0

Related Questions