how to create and update nodes and property using plain cypher query?

324 Views Asked by At

How do I create and update nodes and property using plain cypher query?

Below is my query:

MERGE (c:contact {guid : '500010'})
ON CREATE SET
    c.data_source = '1',
    c.guid = '500010',
    c.created = timestamp()
ON MATCH SET
    c.lastUpdated = timestamp()
MERGE (s:speciality {specialtygroup_desc : 'cold'})
ON CREATE SET s.data_source = '1',
    s.specialtygroup_desc = 'fever',
    s.created = timestamp()
ON MATCH SET s.data_source = '1',
    s.specialtygroup_desc = 'comman cold',
    s.lastUpdated = timestamp()
MERGE (c)-[r:is_specialised_in]->(s)
ON CREATE SET
    r.duration = 1
ON MATCH SET
    r.duration = r.duration + 1

On the first run, node is created as "fever". On the second run, I have updated the specialty_group to "common cold". But it is creating new node with "fever". I am not able to update the "fever" to "common cold". What changes should I make to the above query?

2

There are 2 best solutions below

8
On

The MERGE (s:speciality {specialtygroup_desc : 'cold'}) clause looks for a specialtygroup_desc value of "cold".

During the first execution, that MERGE clause finds no "cold" node -- so it creates one, and the subsequent ON CREATE clause changes it to "fever".

During the second execution, that MERGE again finds no "cold" node (since it is now a "fever" node), so it again creates a "cold" node and the ON CREATE clause yet again changes it to "fever". The ON MATCH clause is never used. This is why you end up with another "fever" node.

Unfortunately, you have not explained your use case in enough detail to offer a recommendation for how to fix your code.

0
On

I think you want to update all node "cold" to "common cold" and if not exists "cold" or "common cold", create new "fever" ? My suggestion:

OPTIONAL MATCH (ss:speciality {specialtygroup_desc : 'cold'}
SET ss.specialtygroup_desc='common cold', ss.lastUpdated = timestamp()
MERGE (c:contact {guid : '500010'})
ON CREATE SET
    c.data_source = '1',
    c.guid = '500010',
    c.created = timestamp()
ON MATCH SET
    c.lastUpdated = timestamp()
MERGE (s:speciality {specialtygroup_desc : 'common cold'})
ON CREATE SET s.data_source = '1',
    s.specialtygroup_desc = 'fever',
    s.created = timestamp()

MERGE (c)-[r:is_specialised_in]->(s)
ON CREATE SET
    r.duration = 1
ON MATCH SET
    r.duration = r.duration + 1