almeynman
almeynman

Reputation: 7398

Neo4J Cypher: Set property only if it is null but still return the node

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

Upvotes: 0

Views: 2379

Answers (3)

Graphileon
Graphileon

Reputation: 5385

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

Upvotes: 1

Thomas Groutars
Thomas Groutars

Reputation: 185

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

Upvotes: 7

Jepser Bernardino
Jepser Bernardino

Reputation: 1372

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

Upvotes: 3

Related Questions