Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add value to array if its not already in there

Tags:

neo4j

cypher

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?

like image 611
J.J Avatar asked Jan 08 '23 23:01

J.J


2 Answers

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
like image 165
Stefan Armbruster Avatar answered Jan 12 '23 16:01

Stefan Armbruster


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
)
like image 36
Mark Amery Avatar answered Jan 12 '23 15:01

Mark Amery