我正在尝试使用py2neo构建一个可变深度的完整二叉树。我一直在尝试使用py2neo事务将create语句发送到服务器,但运行时很糟糕。
构建一个深度为8(255个节点)的树大约需要16.7秒 - 绝大部分时间是在提交事务时花费的(如果在提交之前我是Transaction.process()那么处理占用了运行时的大部分时间)。可能是什么问题? cypher语句只是一个Match和一个节点+关系Create。
这是构建树的函数
def buildBinaryTree(self):
depth = 1
tx = self.graph.begin()
g = self.graph
leaves = []
leaves.append("Root")
tx.run('CREATE(n {ruleName: "Root"})')
timeSum = 0
while depth < self.scale:
newLeaves = []
for leaf in leaves:
leftName = leaf + 'L'
rightName = leaf + 'R'
newLeaves.append(leftName)
newLeaves.append(rightName)
start = timer()
statement = ('MATCH(n {ruleName: "' + leaf + '"}) '
'WITH n CREATE (n)-[:`LINKS TO`]'
'->({ruleName: "' + leftName + '"})')
tx.run(statement)
statement = ('MATCH(n {ruleName: "' + leaf + '"}) '
'WITH n CREATE (n)-[:`LINKS TO`]'
'->(m {ruleName: "' + rightName + '"})')
tx.run(statement)
end = timer()
timeSum += (end - start)
leaves = newLeaves
depth += 1
print("Depth = " + str(depth))
print(timeSum)
start = timer()
print("Processing...")
tx.process()
print (timer() - start)
print("Committing...")
tx.commit()
print("Committed")
print (timer() - start)
并且scale = 8
的输出building tree...
Depth = 2
Depth = 3
Depth = 4
Depth = 5
Depth = 6
Depth = 7
Depth = 8
0.009257960999775605
Processing...
16.753949095999815
Committing...
Committed
17.28687257200022
答案 0 :(得分:0)
尝试进行这些更改,以确保您真正在单个事务中运行,而不是不必要地延迟提交更新:
tx.run
更改为tx.append
。这将使每个Cypher语句排队,而不是立即执行它。tx.process()
,因为您没有后续的Cypher语句入队。理想情况下,您还应该传递参数,而不是每次通过循环修改Cypher语句。但是,这不会导致您遇到的缓慢。