在Python Bolt驱动程序中使用Neo4j事务
我有一些代码使用Python Bolt Neo4j驱动程序成功地创建了一个新节点。但是,我无法在同一事务中创建新关系 我将Python2.7与Neo4j Bolt drive 1.7.2一起使用在Python Bolt驱动程序中使用Neo4j事务,python,neo4j,Python,Neo4j,我有一些代码使用Python Bolt Neo4j驱动程序成功地创建了一个新节点。但是,我无法在同一事务中创建新关系 我将Python2.7与Neo4j Bolt drive 1.7.2一起使用 with conn.session() as session: uuid = getNewUUID() tx = None try: tx = session.begin_transaction()
with conn.session() as session:
uuid = getNewUUID()
tx = None
try:
tx = session.begin_transaction()
stmt = "CREATE (a:{type} {{{uuid_attrib}: $uuid, {name_attrib}: $name, {desc_attrib}: $desc, {has_phi_attrib}: $has_phi}}) RETURN a.{uuid_attrib}".format(
type=ENTITY_NODE_NAME, uuid_attrib=UUID_ATTRIBUTE,
name_attrib=NAME_ATTRIBUTE, desc_attrib=DESCRIPTION_ATTRIBUTE,
has_phi_attrib=HAS_PHI_ATTRIBUTE)
#print "EXECUTING: " + stmt
tx.run(stmt, uuid=uuid, name=name, desc=description, has_phi=hasPHI)
create_relationship(tx, uuid, DERIVED_FROM_REL, parentUUID)
create_relationship(tx, uuid, LAB_CREATED_AT_REL, labCreatedUUID)
create_relationship(tx, uuid, CREATED_BY_REL, createdByUUID)
tx.commit()
return uuid
以下是创建关系的方法:
def create_relationship(tx, startuuid, rel_label, enduuid):
try:
stmt = "MATCH (a),(b) WHERE a.uuid = '$startuuid' AND b.uuid = '$enduuid' CREATE (a)-[r:{rel_label}]->(b) RETURN type(r)".format(
rel_label=rel_label)
temp_stmt = stmt
temp_stmt = temp_stmt.replace("$startuuid", startuuid)
temp_stmt = temp_stmt.replace("$enduuid", enduuid)
print "EXECUTING: " + temp_stmt
result = tx.run(stmt,startuuid=startuuid, enduuid=enduuid)
代码成功地在Neo4j中创建了节点。但是,这些关系从未被创建。我希望将这些关系添加到节点中。如果我将关系创建命令复制并粘贴到bolt web界面,CREATE命令起作用。我不确定这是否是确切的问题,但看起来事务
tx
作为值传递,并且CREATE\u relationship
函数创建自己的tx
本地副本,因此原始tx
不会被函数CREATE\u relationship
修改
提交tx
时,来自create\u relationship
功能的事务不会提交,因为它们不是tx
的一部分
您应该考虑在调用函数本身中运行这些事务,而不是<代码> CREATETIONEXION/CODE >,使用<代码> CREATEY关系> <代码>或类似的函数来创建和返回语句,并在调用函数中运行这些语句。 获取语句的函数:
def get_relationship_statement(startuuid, rel_label, enduuid):
stmt = "MATCH (a),(b) WHERE a.uuid = '$startuuid' AND b.uuid = '$enduuid' CREATE (a)-[r:{rel_label}]->(b) RETURN type(r)".format(
rel_label=rel_label)
temp_stmt = stmt
temp_stmt = temp_stmt.replace("$startuuid", startuuid)
temp_stmt = temp_stmt.replace("$enduuid", enduuid)
print "Statement: " + temp_stmt
return stmt
替换
创建关系(tx、uuid、派生自\u REL、parentUUID)
与
谢谢你,拉杰。你是对的。tx变量的传递值是问题所在。我更改了create_relationship方法,以返回一个包含Cypher语句的字符串,它成功了。再次感谢
tx.run(get_relationship_statement(uuid, DERIVED_FROM_REL, parentUUID),startuuid=uuid, enduuid=parentUUID)