Unable to RETURN nodes after FOREACH in Neo4j Cypher Query

Viewed 571

We are creating a time tree, and this query here works:

CREATE (c:Century {century_label: 2000})
MATCH (c:Century {century_label: 2000})
WITH range(1900,1905) as YEARS, c
FOREACH (year in YEARS | CREATE (y:Year {year_label:year})-[r:YEAR_IN]->(c))

This one doesn't:

CREATE (c:Century {century_label: 2000})
MATCH (c:Century {century_label: 2000})
WITH range(1900,1905) as YEARS, c
FOREACH (year in YEARS | CREATE (y:Year {year_label:year})-[r:YEAR_IN]->(c))
RETURN y as YEAR

The problem is the y as YEAR, Neo4j throws an error about y, so it seems that you cannot do FOREACH and then collect the results after.

What is the proper syntax to return all the created nodes?

1 Answers

I got the answer from the Neo4j Slack:

MATCH (c:Century {century_label:$century})
UNWIND range(1900,1999) as year
CREATE (y:Year {year_label:year})-[r:YEAR_IN]->(c)
RETURN y AS YEAR

Based on my reading as well, I believe this UNWIND is the successor to some of these more antiquated queries. I highly recommend gravitating towards unwind as much as possible.

We see the best performance with it in all tested cases so far.

Related