0
votes

I have written a query which builds 2 new nodes if it exists then it just updates the properties and added a relationship between them.

For the first time when I'm creating the nodes and relationship everything is going fine.

// This is the first run

MERGE (Kunal:PERSON)
ON CREATE SET
    Kunal.name = 'Kunal',
    Kunal.type = 'Person',
    Kunal.created = timestamp()
ON MATCH SET
    Kunal.lastUpdated = timestamp()
MERGE (Bangalore: LOC)
ON CREATE SET
    Bangalore.name = 'Bangalore',
    Bangalore.type = 'Location',
    Bangalore.created = timestamp()
ON MATCH SET
    Bangalore.lastUpdated = timestamp()
MERGE (Kunal)-[r1:LIVES_IN]->(Bangalore)
RETURN * 

enter image description here

Here I'm adding a node Kunal (node) who lives in (relation) Bangalore (node). Everything is fine for the first time.


The next time I'm adding a different node as follows:

// Next time

MERGE (John:PERSON)
ON CREATE SET
    John.name = 'John',
    John.type = 'Person',
    John.created = timestamp()
ON MATCH SET
    John.lastUpdated = timestamp()
MERGE (Bangalore: LOC)
ON CREATE SET
    Bangalore.name = 'Bangalore',
    Bangalore.type = 'Location',
    Bangalore.created = timestamp()
ON MATCH SET
    Bangalore.lastUpdated = timestamp()
MERGE (John)-[r1:LIVES_IN]->(Bangalore)
RETURN *

I am adding a node John who lives in (rel) Bangalore (node).

enter image description here


But the problem here is, its taking the same node value again from the previous merge statement.

Can anybody explain this?

Also what is the solution for this, if let's say if we are running the above merge queries inside of a loop using the Python Driver.

Can't find anything on this tho

1

1 Answers

2
votes

Reason:

The reason lies in your matching pattern of the first and second MERGE statement. Because they only test for the existence of Label Person and Loc, but not a concrete node Person with the name Kunal.

Idea:

As @logisima already explained in the comments of this answer:

"You should always use a MERGE on a primary key (with an index / unique constraint on it)".

Solution:

You should match a concrete, unique node by filtering like {name: 'your content'} or WHERE id(kunal)=1234 for instance.