Artem S.
Artem S.

Reputation: 669

Neo4j add/update property ONLY if node exists. If not then do nothing

It's extiension of question Neo4j Add/update properties if node exists There's answer how to MERGE (create or update) node:

You could set them all at once with a map for all attributes

merge (n:Node {name: 'John'}) set n = {name: 'John', age: 34, coat: 'Yellow', hair: 'Brown'} return n

If you just wanted to replace the attributes age and coat, you could do this instead.

merge (n:Node {name: 'John'}) set n.age = 34, n.coat = 'Yellow' return n

Or you could add it as a map too

merge (n:Node {name: 'John'}) set n += {age: 34, coat: 'Yellow'} return n

Can anyone tell how to UPDATE node ONLY if it exists, but do nothing if node doesn't exists.

Upvotes: 2

Views: 1449

Answers (1)

Tezra
Tezra

Reputation: 8833

The simplest way is

MATCH (n{id:{uuid}) SET n.prop=true

If the match fails, their will be nothing to do the SET against.

Assuming that you would like to still have rows after; (so you can still also return data for a more complex query) You can just make the match optional

...
OPTIONAL MATCH (n{id:{uuid}) SET n.prop=true

Again, if the match fails, n will be null, and the SET will do nothing

Upvotes: 4

Related Questions