The FOREACH
clause is used to update data within a list, whether components of a path, or result of aggregation.
Lists and paths are key concepts in Cypher.
To use them for updating data, you can use the FOREACH
construct.
It allows you to do updating commands on elements in a path, or a list created by aggregation.
The variable context inside of the foreach parenthesis is separate from the one outside it.
This means that if you CREATE
a node variable inside of a FOREACH
, you will not be able to use it outside of the foreach statement, unless you match to find it.
Inside of the FOREACH
parentheses, you can do any of the updating commands — CREATE
, CREATE UNIQUE
, MERGE
, DELETE
, and FOREACH
.
If you want to execute an additional MATCH
for each element in a list then UNWIND
(see Section 10.6, “Unwind”) would be a more appropriate command.
Mark all nodes along a path
This query will set the property marked
to true on all nodes along a path.
Query
MATCH p =(begin)-[*]->(END ) WHERE begin.name='A' AND END .name='D' FOREACH (n IN nodes(p)| SET n.marked = TRUE )
Nothing is returned from this query, but four properties are set.
Result
Properties set: 4 |
---|
|
Try this query live create (_0 {`name`:"A"}) create (_1 {`name`:"B"}) create (_2 {`name`:"C"}) create (_3 {`name`:"D"}) create (_0)-[:`KNOWS`]->(_1) create (_1)-[:`KNOWS`]->(_2) create (_2)-[:`KNOWS`]->(_3) ; match p = (begin)-[*]->(end) where begin.name='A' and end.name='D' foreach(n in nodes(p) | set n.marked = true)