py2neo 到 BOLT:如何将 tx.append 语句转换为 BOLT

py2neo to BOLT: how to convert tx.append statements to BOLT

在 Py2neo 中,可以附加事务,然后将它们作为一个块提交到服务器

from py2neo import Graph
graph = Graph()
tx = graph.cypher.begin()
stmt1 = "CREATE (:Person {name: 'Guinevere'})"
stmt2 = "CREATE (:Person {name: 'Tom'})"
stmt3 = "CREATE (:Person {name: 'Anna'})"
tx.append(stmt)
tx.append(stmt2)
tx.append(stmt3)
tx.commit()

我似乎无法在 BOLT Neo4j 驱动程序手册中找到等效的语法来让它工作。无法识别追加。

driver = GraphDatabase.driver("bolt://localhost",
                                     auth=basic_auth('neo4j', 'password'),
                                     encrypted=True,
                                     trust=TRUST_ON_FIRST_USE)
session = driver.session()    
tx = session.begin_transaction()
tx.append(stmt1) --this does not work
tx.append(stmt2) --this does not work
tx.append(stmt3) --this does not work
tx.commit() --this does not work

正确的做法是什么?

好吧,我已经按照您在下面看到的那样进行了尝试并且成功了:

from neo4j.v1 import GraphDatabase

driver = GraphDatabase.driver("bolt://localhost")

session = driver.session()

stmt1 = "CREATE (:Person {name: 'Guinevere'})"

stmt2 = "CREATE (:Person {name: 'Tom'})"

stmt3 = "CREATE (:Person {name: 'Anna'})"

tx = session.begin_transaction()

tx.run(stmt1) # returned <neo4j.v1.session.StatementResult object at 0x7f3838f77a58>

tx.run(stmt2) # returned <neo4j.v1.session.StatementResult object at 0x7f3838f77a58>

tx.run(stmt3) # returned <neo4j.v1.session.StatementResult object at 0x7f3838f77e10>

tx.commit() # worked ;)

参考: https://neo4j.com/docs/api/python-driver/current/#example

JRenato 的回答确实是正确的。我被运行和追加这个词弄糊涂了。我相信它们的含义略有不同。

我还简化了示例。我的问题源于尝试对另一组附加语句使用相同的连接。看来您需要关闭会话以避免出现问题 - 否则 python 可能会抱怨会话仍处于打开状态以等待新的 begin_transaction()