user1806627
user1806627

Reputation: 160

Neo4j Add/update properties if node exists

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'.

Upvotes: 16

Views: 21607

Answers (3)

Athiramol Sali
Athiramol Sali

Reputation: 1

How to add multiple properties to already existed node

#payload={"query" : 
      " MATCH (t:TvSeries{id:{id})SET t.next_episode_to_air_air_date:
{next_episode_to_air_air_date},next_episode_to_air_episode_number:
{next_episode_to_air_episode_number},next_episode_to_air_id:
{next_episode_to_air_id},next_episode_to_air_name:
{next_episode_to_air_name},next_episode_to_air_overview:
{next_episode_to_air_overview},next_episode_to_air_production_code:
{next_episode_to_air_production_code},next_episode_to_air_season_number:
{next_episode_to_air_season_number},next_episode_to_air_show_id_id:
{next_episode_to_air_show_id},next_episode_to_air_still_path: 
{next_episode_to_air_still_path},next_episode_to_air_vote_average: 
{next_episode_to_air_vote_average},next_episode_to_air_vote_count: 
{next_episode_to_air_vote_count}RETURN t"}

        payload['params'] = params
        response_json = callNeo4j(payload, headers)

Upvotes: -1

Dave Bennett
Dave Bennett

Reputation: 11216

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 

Upvotes: 36

Tezra
Tezra

Reputation: 8833

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

Upvotes: 2

Related Questions