AJN
AJN

Reputation: 1206

neo4j cypher, iterate over the result

I have a neo4j database and I would like to use the result of a part of the cypher code (a set of node ids) to use in the second part:

Something like:

MATCH ()-[:KNOWS]->(b)
FOREACH (n IN distinct(id(b))| SET n :label)

In a pure cypher code, is there a way to loop over the result "distinct(id(b))" and apply to each element another query?

Upvotes: 0

Views: 5262

Answers (2)

jjaderberg
jjaderberg

Reputation: 9952

Two problems with the original query:

  1. You have to have a collection to use FOREACH.
  2. You bind n to a node id, and you can't set labels on node ids, only on nodes.

You can use FOREACH to set labels by doing

MATCH ()-[:KNOWS]->(b)
WITH collect (distinct b) as bb
FOREACH (b IN bb | SET b:MyLabel)

In this case you don't need to do it as a collection, you can just do

MATCH ()-[:KNOWS]->(b)
WITH distinct b
SET b:MyLabel

And in general you can pipe results to an additional query part with WITH

Upvotes: 3

AJN
AJN

Reputation: 1206

I obtained the needed result with:

MATCH ()-[:KNOWS]->(b)
WITH DISTINCT (b)
RETURN id(b)

Upvotes: 0

Related Questions