Cypher 'Node Already Exists' issue with MERGE

前端 未结 1 749
一整个雨季
一整个雨季 2021-02-06 06:14

I am preplexed on why I am getting an issue with this Cypher statment when I have a unique constraint on the address of the location node but am using a merge which should find

相关标签:
1条回答
  • 2021-02-06 06:20

    You've encountered a common misunderstanding of MERGE. MERGE merges on everything you've specified within the single MERGE clause. So the order of operations are:

    1. Search for a :Location node with all of the properties you've specified.
    2. If found, return the node.
    3. If not found, create the node.

    Your problem occurs at step 3. Because a node with all of the properties you've specified does not exist, it goes to step 3 and tries to create a node with all of those properties. That's when your uniqueness constraint is violated.

    The best practice is to merge on the property that you've constrained to be unique and then use SET to update the other properties. In your case:

    MERGE (l:Location {address:"36350 Van Dyke Ave"})
    SET l.location_name = "Starbucks",
         l.city = "Sterling Heights"
    ...
    

    The same logic is going to apply for the relationships you're merging later in the query. If the entire pattern doesn't exist, it's going to try to create the entire pattern. That's why you should stick to the best practice of:

    MERGE (node1:Label1 {unique_property: "value"})
    MERGE (node2:Label2 {unique_property: "value"})
    MERGE (node1)-[:REL]-(node2)
    
    0 讨论(0)
提交回复
热议问题