harshvardhan
harshvardhan

Reputation: 805

Can we use MERGE in Cypher to update a node property?

I am aggregating a dataset into neo4j graph and have written a python script for it, using py2neo through which I execute cypher queries.

Consider a situation where where I have a node of the type "item" with properties "type" and "count" and lets say I have 5 different type of items.

My script iterates over the dataset and this is what it does:

  1. Checks if the "item" node of the type exists.
  2. (a) If exists, then extracts its "count", increases it by 1 and updates the property value (b) If does not exist, then create the "item" node of current "type" and assigns it a "count" of 1. I am not using MERGE till now.

I know the separate steps 1 and 2(b) can be clubbed using MERGE. That means cypher will check for the pattern

(n:item{type:"detergent", count:1})

And if it is not existing, will create.

What I want to know from cypher masters here is, can I use MERGE to even update the property value? Specifically, if after 10 iterations through the dataset, if the count of detergent has become 4, from the procedure I am using right now, can I replace that procedure to use MERGE so that the following purpose is solved:

1) if detergent appears in iteration, cypher should create a node for detergent with count 1 if the node for detergent does not exist.

2) if detergent appears in iteration, cypher should increase the count property by 1 if the node for detergent already exists.

Upvotes: 2

Views: 709

Answers (1)

SylvainRoussy
SylvainRoussy

Reputation: 359

Could you try :

MERGE (n:item{type:"detergent") 
ON CREATE SET n.count=1 
ON MATCH SET n.count=n.count+1

ON CREATE : when the node doesn't exist ON MATCH : when the node is found in the graph

Hope helping.

Upvotes: 4

Related Questions