Tarendran Vivekananda
Tarendran Vivekananda

Reputation: 15

neo4j: If statement for deleting nodes based on relationships

I am trying to delete the nodes that has a relationship to each other node if the relationship exist. If the relationship doesnt exist delete the first node. Example: I am using UNWIND because that is the data provided by the user.

UNWIND [{name:'John'}] as rows
IF EXISTS(u:Person)-[r:OWNS]->(c:Car), THEN
MATCH (u:Person)-[r:OWNS]->(c:Car)
WHERE u.user_name = rows.name
DETACH DELETE u,c
OTHERWISE
MATCH (u:Person)
WHERE u.user_name = rows.name
DETACH DELETE u

I tried using apoc.do.when however they dont allow EXISTS(u:User)-[r:OWNS]->(c:Car) as a conditional statement.

Upvotes: 0

Views: 402

Answers (2)

cybersam
cybersam

Reputation: 66999

This query using pattern comprehension should work:

UNWIND [{name:'John'}] as rows
MATCH (u:Person)
WHERE u.user_name = rows.name
FOREACH(x IN [(u)-[:OWNS]->(c:Car)|c] | DETACH DELETE x)
DETACH DELETE u

Upvotes: 0

Tomaž Bratanič
Tomaž Bratanič

Reputation: 6514

You can probably do this without the APOC library and just use the OPTIONAL MATCH clause.

UNWIND [{name:'John'}] as rows
// Match the person
MATCH (u:Person)
WHERE u.user_name = rows.name
// Check if she/he owns any car
OPTIONAL MATCH (u)-[:OWNS]->(c:Car)
// Delete them all
DETACH DELETE u,c

I've checked and cypher has no problem if sometimes there will be null as variable c.

You can check this by doing:

DETACH DELETE null

It doesn't return any error, so I think it should work fine.

Upvotes: 0

Related Questions