FOREACH

Lists and paths are key concepts in Cypher®. The FOREACH clause can be used to update data, such as executing update commands on elements in a path, or on a list created by aggregation.

The variable context within the FOREACH parenthesis is separate from the one outside it. This means that if you CREATE a node variable within a FOREACH, you will not be able to use it outside of the foreach statement, unless you match to find it.

Within the FOREACH parentheses, you can do any of the updating commands — SET, REMOVE, CREATE, MERGE, DELETE, and FOREACH.

If you want to execute an additional MATCH for each element in a list then the UNWIND clause would be a more appropriate command.

graph foreach clause

Mark all nodes along a path

This query sets the property marked to true on all nodes along a path.

Query
MATCH p=(start)-[*]->(finish)
WHERE start.name = 'A' AND finish.name = 'D'
FOREACH (n IN nodes(p) | SET n.marked = true)
Table 1. Result

(empty result)

Rows: 0
Properties set: 4

Mark all relationships along a path

This query sets the property marked to true on all relationships along a path.

MATCH p=(start)-[*]->(finish)
WHERE start.name = 'A' AND finish.name = 'D'
FOREACH ( r IN relationships(p) | SET r.marked = true )
Table 2. Result

(empty result)

Rows: 0
Properties set: 3

Create new nodes from a list of name labels

This query creates a new node for each label in a list.

Query
WITH ['E', 'F', 'G'] AS names
FOREACH ( value IN names | CREATE (:Person {name: value}) )
Table 3. Result

(empty result)

Rows: 0
Nodes created: 3