如何从python获取cypher查询的执行时间?

时间:2018-04-16 14:07:06

标签: python neo4j cypher neo4j-driver

我试图比较从python获取Cypher查询的执行时间,即在neo4j服务器上计算所需的时间(不包括输出结果所需的时间)。现在我使用以下代码:

from neo4j.v1 import 
driver = GraphDatabase.driver('bolt://localhost:7687', auth=('neo4j', '1234'))

n_repeats = 3
cypher = "MATCH (a) -[:{}*]- (b) WHERE ID(a) < ID(b) RETURN DISTINCT a, b".format(graphname + '_edges')

with driver.session() as session:
    total_time = 0
    for _ in range(n_repeats):
        with session.begin_transaction() as tx:
            start = time.time()
            tx.run(cypher)
            total_time += time.time() - start

avg_time = total_time*1000 / n_repeats
print('Average execution time:', avg_time, 'ms')

有没有更好的方法来计算密码查询的执行时间?例如,在postgresql中有EXPLAIN ANALYZE语句,它还提供执行SQL查询所需的时间。在Cypher中有EXPLAIN和PROFILE语句,但两者似乎都没有返回特定时间。

我现在正在使用neo4j-driver连接到neo4j,但我愿意切换到另一个库。

2 个答案:

答案 0 :(得分:1)

事实上,所有结果都可以使用所需的时间而不进行分析。它们位于结果摘要中,执行时间分为直到任何结果流可用的时间和服务器使用整个结果流的时间。

可以将它们加在一起以获得查询的总执行时间,以毫秒表示:

result = tx.run(query, params)
avail = result.summary().result_available_after
cons = result.summary().result_consumed_after
total_time = avail + cons

答案 1 :(得分:0)

Neo4j Python驱动程序1.7

from neo4j.v1 import 
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))

n_repeats = 3
cypher = "MATCH (a) -[:{}*]- (b) WHERE ID(a) < ID(b) RETURN DISTINCT a, b".format(graphname + '_edges')

with driver.session() as session:
    total_time = 0
    for _ in range(n_repeats):
        with session.begin_transaction() as tx:
            start = time.time()
            result = tx.run(cypher)
            records = list(result)  # consume the records
            tx.commit()
            total_time += time.time() - start

avg_time = total_time*1000 / n_repeats
print('Average execution time:', avg_time, 'ms')