Neo4J-优化3个合并查询到单个查询 [英] Neo4J - Optimizing 3 merge queries into a single query
问题描述
我正在尝试进行一个Cypher查询,该查询使2个节点并在它们之间添加关系.
要添加节点,我正在检查该节点是否存在,如果存在,那么我只是继续并设置属性.
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 *
问题是这些是3个单独的查询,当我通过Python驱动程序运行它时将有3个数据库调用.有没有一种方法可以将这些查询优化为单个查询.
推荐答案
当然,您可以将三个查询连接为一个.
在这种情况下,您可以省略上一个查询的第一个和第二个MERGE
,因为新查询已经开始了.
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 *
这篇关于Neo4J-优化3个合并查询到单个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!