使用 py2neo 上传数据的最佳方式



我已经尝试了使用 py2neo 上传中型数据集的方法。就我而言,每天需要加载大约 80 K 节点和 400 K 边。我想分享我的经验,并询问社区是否还有我没有遇到的更好的方法。

A. py2neo的"本机"命令。

使用 graph.merge_one() 创建节点并使用 push() 设置属性。我很快就忽略了这一点,因为它非常慢,甚至不会在几分钟内超过 10 K 记录。毫不奇怪,py2neo的文档和这里的一些帖子推荐Cypher。

B. 不分区的密码

在循环中使用py2neo.cypher.CypherTransaction append(),最后使用commit()

# query sent to MSSQL. Returns ~ 80K records
result = engine.execute(query) 
statement = "MERGE (e:Entity {myid: {ID}}) SET e.p = 1"
# begin new Cypher transaction
tx = neoGraph.cypher.begin()
for row in result:
    tx.append(statement, {"ID": row.id_field})
tx.commit()

这会超时并使 Neo4j 服务器崩溃。我知道问题是所有 80 K Cypher 语句都试图一次性执行。

C. 具有分区和一次提交的密码

我使用计数器和process()命令一次运行 1000 个语句。

# query sent to MSSQL. Returns ~ 80K records
result = engine.execute(query) 
statement = "MERGE (e:Entity {myid: {ID}}) SET e.p = 1"
counter = 0
tx = neoGraph.cypher.begin()
for row in result:
    counter += 1
    tx.append(statement, {"ID": row.id_field})
    if (counter == 1000):
        tx.process()    # process 1000 statements
        counter = 0
tx.commit()

这在开始时运行得很快,但在处理 1000 个事务时会变慢。最终,它会在堆栈溢出中超时。这很令人惊讶,因为我预计process()每次都会重置堆栈。

D. 具有分区和每个分区提交的

密码

这是唯一运行良好的版本。对每个包含 1000 个事务的分区执行commit(),并使用 begin() 重新启动新事务。

# query sent to MSSQL. Returns ~ 80K records
result = engine.execute(query) 
statement = "MERGE (e:Entity {myid: {ID}}) SET e.p = 1"
counter = 0
tx = neoGraph.cypher.begin()
for row in result:
    counter += 1
    tx.append(statement, {"ID": row.id_field})
    if (counter == 1000):
        tx.commit()                   # commit 1000 statements
        tx = neoGraph.cypher.begin()  # reopen transaction
        counter = 0
tx.commit()

这运行得又快又好。

有什么意见吗?

正如您通过反复试验发现的那样,单个事务在操作不超过 10K-50K 时表现最佳。在 D 中描述的方法效果最好,因为每 1000 个语句提交一次事务。您可能可以安全地增加该批大小。

您可能想要尝试的另一种方法是将值数组作为参数传递,并使用 Cypher 的 UNWIND 命令对其进行迭代。例如:

WITH {id_array} AS ids // something like [1,2,3,4,5,6]
UNWIND ids AS ident
MERGE (e:Entity {myid: ident})
SET e.p = 1

最新更新