Neo4J - Merge statement not creating new nodes with a relationship

南笙酒味 提交于 2021-02-08 11:44:15

问题


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 * 

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


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:


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.



来源:https://stackoverflow.com/questions/53557715/neo4j-merge-statement-not-creating-new-nodes-with-a-relationship

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!