Set only if condition satisfies but return the matched node


(Ashwin Dinesh01) #1

I need to do a match then set a value if condition satisfies and then return the node.

I have tried the following:

MATCH (n:node {uid: "myid"})
WHERE (NONE(x IN n.arr WHERE x = "newentry") SET n.arr = n.arr + "newentry")
RETURN n;

The problem with this statement is that it will not return the node if "newentry" already exists in n.arr. But at the same time, I only want to add the new entry if it does not exist in n.arr. Irrespective of whether new entry was added or not, I have to return the node if there is a match.

Please help me with this.


(Michael Hunger) #2

you can just change your expression to a case

MATCH (n:node {uid: $id})
SET n.arr = case when $value IN n.arr then n.arr else n.arr + $value end
RETURN n

you can also use FOREACH for more complex nested conditionals

MATCH (n:node {uid: $id})
FOREACH (_ IN case when $value in n.arr then [] else [true] end |
  SET n.arr = n.arr + $value
)
RETURN n;

(Ashwin Dinesh01) #3

Thank you @michael.hunger. I did not know we can use the 'case when' in the 'set' clause.


(Michael Hunger) #4

case ... end is an expression so you can use it anywhere you use another expressions too.