0
votes

I am quite new to Neo4J and struggling with the following:

I want to set property only if it does not exist yet (if it's null) and do not want to set property if it exists. How can I modify the query below to achieve that

  MATCH (u:User)
  WHERE u.uuid=$userId
  SET u.unsubscribedAt = timestamp()
  RETURN u

Thanks in advance

UPDATE 1: One thing I forgot to mention: I still want to return the node regardless, so cannot add AND u.unsubscribedAt is null in where clause

3

3 Answers

4
votes

You can use coalesce to achieve this. It returns the first non-null value it's passed, so it will resolve the existing value if already present

  MATCH (u:User)
  WHERE u.uuid=$userId
  SET u.unsubscribedAt = coalesce(u.unsubscribedAt, timestamp())
  RETURN u
3
votes

What about adding the property as a discriminator for the match?

  MATCH (u:User)
  WHERE u.uuid=$userId AND IS NULL u.unsubscribedAt
  SET u.unsubscribedAt = timestamp()
  RETURN u
1
votes

if you do not mind the property being overwritten with its original value, you could also do this :

MATCH (u:User {uuid:$userId})
SET u.unsubscribedAt = COALESCE(u.unsubscribedAt,timestamp())
RETURN u