Neo4j Add/update properties if node exists

2020-02-23 08:31发布

问题:

I want to be able to update/enlarge my Neo4j database by uploading a newer version of that database OR part of that database.

Of what I've found I can use MERGE to add new nodes just if they don't already exists. But in that process, how do I in a slimmed way add new properties to that existing node if they don't exist?

I e, if I have a node 'John' of 'Age:34' and 'Hair:brown' and upload 'John'/'Age:34'/'Coat:Yellow' - how do I get 'John'/'Age:34'/'Hair:brown'/'Coat:Yellow'.

回答1:

You could merge the node on John (or the primary identifying attribute). And then set the properties after the successful merge.

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 


回答2:

MERGE guarantees that a node will exist afterwards (either matched or created). If you don't want to create the node, you need to use MATCH instead. (Since you say "if node exists", that implies it shouldn't be created)

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; (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



标签: neo4j cypher