I want to add a value to an array if its not already there.
So far my code looks something like this (note that both r.names and {name} are arrays, and [1] + [2] = [1,2]):
MERGE (r:resource {hash:{hash}})
ON CREATE SET r.names = {name}
ON MATCH SET r.names = r.names + {name}
but obviously if {name} is already in r.names, it just gets added again. How can I add {name} only if r.names doesn't already contain it?
I guess you need to use the FOREACH + CASE WHEN trick: using a case when you use either a 1 element array (if your condition is true) or a 0 element array otherwise as iterator used in FOREACH. FOREACH cannot be used in a ON MATCH or ON CREATE handler, so we put it after the MERGE and use a coalesce to cover the case when r.names does not yet exist:
MERGE (r:Resource {hash:{hash}})
FOREACH(x in CASE WHEN {name} in r.names THEN [] ELSE [1] END |
SET r.names = coalesce(r.names,[]) + {name}
)
RETURN r.names
Use FILTER to get an array of the elements that aren't already in r.names and add them:
MERGE (r:resource {hash:{hash}})
ON CREATE SET r.names = {new_names}
ON MATCH SET r.names = r.names + FILTER(
el FOR el in {new_names} IF NOT el IN r.names
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With