0
votes

I'm trying to use Neo4j Cypher to implement the following function: given a node, check if it has any outgoing edges with a specific relationship type. If so, return the nodes it can reach out by those edges, otherwise delete this node. And my code is like this

MATCH (m:Node{Properties})
WITH (size((m)-[:type]->(:Node))) AS c,m 
WHERE c=0
DETACH DELETE m

However I don't know how to apply the if/else condition here, and this code only implements part of what I need. I'd really appreciate your help and suggestions!

For example the database is like this:

A-[type]->B

A-[type]->C

If the original node is A and it has two edges with that type to B and C, then I want the query to return B and C as result. If the original node is B, it should be deleted because there's no such outgoing edge from B.

1
You will probably want to use APOC conditional proceduresTomaž Bratanič
Thanks for your suggestion, but I have some issues using APOC query in java..it always got some errosBrandNewStory
well, we can always help you with that :)Tomaž Bratanič

1 Answers

0
votes

[UPDATED]

The following query uses a FOREACH hack to conditionally delete m, and returns either the found n nodes, or NULL if there were none.

OPTIONAL MATCH (m:Node {...Properties...})-[:type]->(n:Node)
FOREACH(x IN CASE WHEN n IS NULL THEN [1] END | DETACH DELETE m)
RETURN n

You could also use the APOC procedure apoc.do.when instead of the FOREACH hack:

OPTIONAL MATCH (m:Node {...Properties...})-[:type]->(n:Node)
CALL apoc.do.when(n IS NULL, 'DETACH DELETE m', '', {m: m}) YIELD value
RETURN n