Neo4j/Cypher FOREACH square brackets and use of "THEN [1]"

455 Views Asked by At

I have seen multiple examples of cypher FOREACH statements that reference the number 1 in square brackets and I cannot find documentation on it. This is a working statement:

FOREACH(i in CASE WHEN NOT rel IS NULL THEN [1] ELSE [] END |
DELETE rel CREATE (newest)-[:NEXT_SUB_REPLY]->(prevNewest))

and as happy as I am that it is working, I would like to understand more about the use of square brackets and the use of the number 1. From the context I understand that it loops through and when

CASE WHEN NOT rel IS NULL

is true, it executes

DELETE rel CREATE (newest)-[:NEXT_SUB_REPLY]->(prevNewest)

and otherwise it does nothing. The Neo4j docs are very light on FOREACH and don't go into either the use of square brackets or using a 1 in the THEN clause.

1

There are 1 best solutions below

1
On BEST ANSWER

It's a bit of a hack to support conditional execution of a statement. Essentially, it's equivalent to the following pseudocode:

IF (rel IS NOT NULL) THEN {
   DELETE rel CREATE (newest)-[:NEXT_SUB_REPLY]->(prevNewest))
}

FOREACH will iterate over a collection and execute some operation for each element of the collection. If there are no elements in the collection, the operation won't run. If there's one element in the collection, it'll run once.

As for why it's [1] in the query, it actually doesn't matter and it's basically just convention and down to personal taste. It would work the same way with any one-element collection - for example [true] or [null] should both suffice. The important thing is that truthy leg of the CASE statement returns a one-element array, and otherwise a zero-element array.

The docs have more information, as well as (arguably) less unreadable alternatives if you're willing to take a dependency on the APOC library.