How to set a property if not exists array in neo4j

i want to add properties in array if a value not in the array.

CREATE (n:Test { my_array:['a', 'b', 'c']}) RETURN n;

Here i would like check my_array values and add 'new_value' like 'd' which is not in the list. Please help to add this attribute.

Hello @kmanimuthu and welcome to the Neo4j community :slight_smile:

CREATE (n:Test {my_array: ['a', 'b', 'c']})
SET (CASE WHEN 'd' NOT IN n.my_array THEN n END).my_array = my_array + ['d']
RETURN n

Regards,
Cobra

Hi @maxime.guery.contact, Thanks for your point. I got a clue from your code and below code is working fine for me.

MATCH (n:Test)
SET n.my_array = case when 'd' IN n.my_array then n.my_array else n.my_array + 'd' end
RETURN n

But i tried the same by using 'NOT IN' it gives error.

MATCH (n:Test)
SET n.my_array = case when 'd' NOT IN n.my_array then n.my_array + 'd' else n.my_array end
RETURN n

I am not sure what is wrong when use 'NOT IN'. Some one could help to resolve that error.

Thanks,
Manimuthu

This query should work:

MATCH (n:Test)
SET n.my_array = CASE WHEN NOT 'd' IN n.my_array THEN n.my_array + 'd' ELSE n.my_array END
RETURN n

Regards,
Cobra

1 Like

Thanks @maxime.guery.contact. It's works as expected.

1 Like