Hi All,
I just started playing around with Neo4j and trying to learn Cypher. I've been stuck on getting a certain behavior and I'm sure there's probably a simple solution that I'm missing.
I've attached a screenshot of some sample data and I'll try my best to explain but I'm trying to accomplish.
First, the constraints...Every "Home" can only have one "Parent" and one "Parent" can have only 6 "Children".
So when the query is first ran, I'm given a "Parent" id. I need to query the data to see if the parent ID already exists, if it doesn't, I need to create a new Parent Node and a relationship to a "HOME" that doesn't have any Parents attached, but only to one of the Homes (not all of them).
Then when the data is queried again using the same "Parent" id, I need to create a "Child" Node and a relationship to the parent with the specific id. However, if the "Parent" already has 6 Children, I need to find a home with 0 Parents, create a new Parent to that home and also create a child to that parent.
This is the query I have worked out but doesn't do exactly what I'm trying to accomplish.
Match(h:Home)-[:IN]->(s:State) WHERE s.name = "California"
Optional Match(p:Parent) where p.id = "parent-uuid"
Optional Match(child:Child)-[l:LIVES_WITH]->(newParent:Parent) WHERE p.id = "parent-uuid"
WITH p as p, count(l) as counts, h as h
LIMIT 1
WHERE counts < 6
CALL apoc.do.when(
p IS NULL, 'CREATE (newParent:Parent {id: "parent-uuid"}), (newParent)-[:RUNS]->(h) RETURN h.id',
'CREATE (child:Child {id: "child-uuid"}), (child)-[:LIVES_WITH]->(p) RETURN h.id',
{p:p, counts:counts, h:h})
YIELD value
RETURN value
When I run the query the first time, it does create a new Parent node and attaches it to a home, and when I run it 6 more times, I do get 6 children attached to the parent.
However, after 6 children are attached to a parent, it doesn't try to find another home with 0 parents and then create child, parent, and relationships (child-[:LIVES_WITH]-parent-[:RUNS]-home).
Also, if I were to query for a different parent uuid, the query will attach that new parent to a home with an already existing parent, which I don't want. It should go to a home with 0 parents.
I hope that makes sense and I'm happy to clarify. Any help would be greatly appreciated, thank you!