cancel
Showing results for 
Search instead for 
Did you mean: 

Using variable inside foreach

ri8ika
Graph Voyager
MATCH (n:Node)
// ....
// keys => ['foo', 'bar']
FOREACH (k IN keys | SET n.k = 'something')
> variable n is not defined

What I'm trying to do is something like:

n.foo = 'something'
n.bar = 'something'
1 ACCEPTED SOLUTION

WITH controls variable scope, so anything not included in the WITH clause is out of scope, thus your error.

Include n (and any other variables you need to work with past that point) in your WITH and you should be fine.

View solution in original post

6 REPLIES 6

Could we see the full query? Are there any WITH clauses between the match to n and the FOREACH? And if so is n always included in the WITH?

Also what version of Neo4j?

Yes, it is.

WITH [....] as keys

Is using WITH keyword ignores variables defined in upper code. How can we include them in the WITH?

I am using latest version of neo4j.

WITH controls variable scope, so anything not included in the WITH clause is out of scope, thus your error.

Include n (and any other variables you need to work with past that point) in your WITH and you should be fine.

ri8ika
Graph Voyager

One last thing:

SET n.k

is setting k as property instead of foo. Am I doing something wrong here?

FOREACH (k IN keys | SET n.k = 'something')

Whereas, keys consist of ['foo','bar'].

Dot references like n.k are always literal, so this is about setting the k property of an n node, this won't be set dynamically.

Dynamic property setting isn't allowed in this way.

If you know the keys ahead of time ('foo' and 'bar' in this case), we can assemble a map of these keys and the new values, and use the += operator to update the values according to the map:

WITH {foo:'something', bar:'somethingElse'} as update
MATCH (n:Node)
// ....
SET n += update

ri8ika
Graph Voyager

Anyways, I have solved my issue other tricky way. Thanks for your replies.