FOREACH
Generic Description
Iterate over a list and apply update clauses to each element.
Simple example:
MATCH (n) WITH collect(n) AS ns FOREACH (x IN ns | SET x.touched = true)
Consumer-Level Explanation
Use FOREACH when the query must iterate over a list and apply update clauses to each element and the planner needs to see that operation as part of the Cypher row pipeline. Keep the clause explicit because it controls row grain, variable scope, and what later clauses are allowed to reference.
More Detailed Explanation
FOREACH is update-oriented control flow in Cypher. It becomes especially valuable when a query naturally produces a list that then needs systematic mutation. In Nexyron it sits at the boundary between expression/list work and graph mutation work.
What this clause is really for:
- it defines one concrete stage in the Cypher row pipeline, so variables available before and after
FOREACHmust be clear - it should make graph structure, temporal filters, document payload shaping, or procedure output explicit instead of relying on client-side interpretation
- planner tooling depends on this clause boundary to know row grain, variable scope, and whether later expressions are reads, writes, schema operations, or projections
Advanced Example
This example keeps FOREACH inside a complete query pipeline so the clause boundary, visible variables, and returned row shape are clear to planner tooling.
UNWIND [{user_id: 'u-1', doc_id: 'd-1', ts: '2025-01-02T10:00:00Z', payload: {kind: 'view'}, doc_metadata: {kind: 'report'}, embedding: [0.22, 0.18, 0.44]}] AS evt
MERGE (u:User {user_id: evt.user_id})
MERGE (d:Document {doc_id: evt.doc_id})
CREATE (u)-[e:VIEWED]->(d)
SET e.ts = toDateTime(evt.ts),
e.payload = evt.payload,
d.metadata = evt.doc_metadata,
d.embedding = vector(evt.embedding)
WITH u, d, e, date_trunc('day', e.ts) AS day_bucket
RETURN u.user_id, d.doc_id, day_bucket, keys(properties(d)) AS doc_keys
Real Use Cases
- bulk mutation over collected rows
- fan-out creation from precomputed lists
- post-processing tags or flags after a discovery step
Real Limitations And Tradeoffs
- it is for update clauses, not general row-returning logic
- large lists can turn into heavy mutation bursts
- hard-to-read FOREACH bodies should usually be simplified with WITH stages