我有一棵存储在Neo4j中的树,在树中,每个节点都包含一个标识符和一个计数器。我希望能够快速地增加一堆节点的计数器。所以我使用了MERGE(带有ON CREATE SET和ON MATCH SET),但是性能相当差。而且似乎如果我用两个事务来执行它,一个用于知道每个节点是否存在,另一个用于创建或更新它,会更快。您知道为什么MERGE比MATCH和CREATE组合要慢吗?我如何提高它的性能?下面是一个相关的示例,您可以复制执行:
感谢您的帮助 :)
import datetime
from py2neo import Graph
def bench(query, count, reset=True):
graph = Graph()
if reset:
graph.cypher.run("MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n,r")
graph.cypher.run("CREATE CONSTRAINT ON (node:Node) ASSERT node.number IS UNIQUE")
graph.cypher.run("CREATE (r:Root)")
start = datetime.datetime.now()
tx = graph.cypher.begin()
for i in range(count):
tx.append(query, {'i': i})
tx.commit()
print('---')
print('query : %s' % query)
print("%i create. %s/second." % (count, count // (datetime.datetime.now() - start).total_seconds()))
if __name__ == '__main__':
bench("MATCH (:Root)-[:Child]->(n:Node {number: {i}}) RETURN n.count", 1000)
bench("CREATE (:Root)-[:Child]->(:Node {number: {i}, count: 1})", 1000)
bench("MATCH (root:Root) CREATE (root)-[:Child]->(:Node {number: {i}, count: 1})", 1000)
bench("MATCH (root:Root) MERGE (root)-[:Child]->(n:Node {number: {i}}) ON CREATE SET n.count = 1 ON MATCH SET n.count = n.count + 1", 1000)
bench("MATCH (root:Root)-[:Child]->(n:Node {number: {i}}) SET n.count = n.count + 1", 1000)
bench("MATCH (root:Root) CREATE UNIQUE (root)-[:Child]->(n:Node {number: {i}}) SET n.count = coalesce(n.count, 0) + 1", 1000)
这段代码的输出:
---
query : MATCH (:Root)-[:Child]->(n:Node {number: {i}}) RETURN n.count
1000 create. 1151.0/second.
---
query : CREATE (:Root)-[:Child]->(:Node {number: {i}, count: 1})
1000 create. 760.0/second.
---
query : MATCH (root:Root) CREATE (root)-[:Child]->(:Node {number: {i}, count: 1})
1000 create. 1092.0/second.
---
query : MATCH (root:Root) MERGE (root)-[:Child]->(n:Node {number: {i}}) ON CREATE SET n.count = 1 ON MATCH SET n.count = n.count + 1
1000 create. 218.0/second.
---
query : MATCH (root:Root)-[:Child]->(n:Node {number: {i}}) SET n.count = n.count + 1
1000 create. 3005.0/second.
---
query : MATCH (root:Root) CREATE UNIQUE (root)-[:Child]->(n:Node {number: {i}}) SET n.count = coalesce(n.count, 0) + 1
1000 create. 283.0/second.
感谢您的帮助 :)