Neo4j 简明教程
Neo4j - Foreach Clause
FOREACH 子句用于更新列表中的数据,无论这些数据是路径的组件还是聚合的结果。
The FOREACH clause is used to update data within a list whether components of a path, or result of aggregation.
Syntax
以下是 FOREACH 子句的语法。
Following is the syntax of the FOREACH clause.
MATCH p = (start node)-[*]->(end node)
WHERE start.node = "node_name" AND end.node = "node_name"
FOREACH (n IN nodes(p)| SET n.marked = TRUE)
Example
在继续示例之前,请按如下所示在 Neo4j 数据库中创建一个路径 p 。
Before proceeding with the example, create a path p in Neo4j database as shown below.
CREATE p = (Dhawan {name:"Shikar Dhawan"})-[:TOPSCORRER_OF]->(Ind{name:
"India"})-[:WINNER_OF]->(CT2013{name: "Champions Trophy 2013"})
RETURN p
以下是一个使用 FOREACH 子句为路径中的所有节点添加属性的示例 Cypher 查询。
Following is a sample Cypher Query which adds a property to all the nodes along the path using the FOREACH clause.
MATCH p = (Dhawan)-[*]->(CT2013)
WHERE Dhawan.name = "Shikar Dhawan" AND CT2013.name = "Champions Trophy 2013"
FOREACH (n IN nodes(p)| SET n.marked = TRUE)
执行上述查询,执行以下步骤:
To execute the above query, carry out the following steps −
Step 1 - 打开 Neo4j Desktop App 并启动 Neo4j Server。使用 URL http://localhost:7474/ 打开 Neo4j 的内置浏览器应用,如下面的屏幕截图所示。
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.

Step 2 - 在美元提示符中复制并粘贴所需的查询,并按播放按钮(执行查询)突出显示在下面的屏幕截图中。
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.

Verification
要验证节点的创建,请在美元提示符中键入并执行以下查询。
To verify the creation of the node, type and execute the following query in the dollar prompt.
MATCH (n) RETURN n
此查询返回数据库中的所有节点(我们将在即将到来的章节中详细讨论此查询)。
This query returns all the nodes in the database (we will discuss this query in detail in the coming chapters).
执行此查询后,将显示创建的节点,如下图所示。
On executing, this query shows the created node as shown in the following screenshot.
