Search code examples
neo4jcypher

Add value to array if its not already in there


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?


Solution

  • 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