Question

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?

Was it helpful?

Solution

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

OTHER TIPS

I obtained the needed result with:

MATCH ()-[:KNOWS]->(b)
WITH DISTINCT (b)
RETURN id(b)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top