Neo4J - Optimizing 3 merge queries into a single query

末鹿安然 提交于 2019-12-23 05:05:49

问题


I am trying to make a Cypher query which makes 2 nodes and adds a relationship between them.

For adding a node I'm checking if the node is existing or not, if existing then I'm simply going ahead and setting a property.

// Query 1 for creating or updating node 1

MERGE (Kunal:PERSON)
ON CREATE SET
    Kunal.name = 'Kunal',
    Kunal.type = 'Person',
    Kunal.created = timestamp()
ON MATCH SET
    Kunal.lastUpdated = timestamp()
RETURN Kunal

// Query 2 for creating or updating node 2

MERGE (Bangalore: LOC)
ON CREATE SET
    Bangalore.name = 'Bangalore',
    Bangalore.type = 'Location',
    Bangalore.created = timestamp()
ON MATCH SET
    Bangalore.lastUpdated = timestamp()
RETURN Bangalore

Likewise I am checking if a relationship exists between the above created nodes, if not exists then creating it else updating its properties.

// Query 3 for creating relation or updating it.

MERGE (Kunal: PERSON { name: 'Kunal', type: 'Person' })
MERGE (Bangalore: LOC { name: 'Bangalore', type: 'Location' })
MERGE (Kunal)-[r:LIVES_IN]->(Bangalore)
ON CREATE SET
    r.duration = 36
ON MATCH SET
    r.duration = r.duration + 1 
RETURN *

The problem is these are 3 separate queries which will have 3 database calls when I run it via the Python driver. Is there a way to optimize these queries into a single query.


回答1:


Of course you can concatenate your three queries to one. In this case you can omit the first and second MERGE of your last query, because it is assured by the start of new query already.

MERGE (kunal:PERSON {name: ‘Kunal'})
ON CREATE SET
    kunal.type = 'Person',
    kunal.created = timestamp()
ON MATCH SET
    kunal.lastUpdated = timestamp()
MERGE (bangalore:LOC {name: 'Bangalore'})
ON CREATE SET
    bangalore.type = 'Location',
    bangalore.created = timestamp()
ON MATCH SET
    bangalore.lastUpdated = timestamp()
MERGE (kunal)-[r:LIVES_IN]->(bangalore)
ON CREATE SET
    r.duration = 36
ON MATCH SET
    r.duration = r.duration + 1 
RETURN *


来源:https://stackoverflow.com/questions/53556628/neo4j-optimizing-3-merge-queries-into-a-single-query

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