FOREACH

Introduction

Lists and paths are key concepts in Cypher®. FOREACH 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 — CREATE, CREATE UNIQUE, MERGE, DELETE, and FOREACH.

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

Graph
  N0 [
    label = "{Person|name = \'A\'\l}"
  ]
  N0 -> N1 [
    color = "#2e3436"
    fontcolor = "#2e3436"
    label = "KNOWS\n"
  ]
  N1 [
    label = "{Person|name = \'B\'\l}"
  ]
  N1 -> N2 [
    color = "#2e3436"
    fontcolor = "#2e3436"
    label = "KNOWS\n"
  ]
  N2 [
    label = "{Person|name = \'C\'\l}"
  ]
  N2 -> N3 [
    color = "#2e3436"
    fontcolor = "#2e3436"
    label = "KNOWS\n"
  ]
  N3 [
    label = "{Person|name = \'D\'\l}"
  ]

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.

Table 1. Result

(empty result)

0 rows
Properties set: 4