在Python Bolt驱动程序中使用Neo4j事务

时间:2019-04-21 18:59:53

标签: python neo4j

我有一些代码可以使用Python Bolt Neo4j驱动程序成功创建一个新节点。但是,我无法在同一笔交易中创建新的关系。

我正在将Python 2.7和Neo4j Bolt驱动器1.7.2一起使用。

    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

这是create_relationship方法:

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中创建了节点。但是,从不创建关系。我希望将关系添加到该节点。如果我将关系CREATE命令复制并粘贴到bolt Web界面中,则CREATE命令有效。

1 个答案:

答案 0 :(得分:1)

我不确定这是否是确切的问题,但是看起来交易tx作为值传递,并且create_relationship函数创建了自己的tx本地副本,因此原始{{1 }}未被函数tx修改。

提交create_relationship时,不会提交来自tx函数的事务,因为这些事务不属于create_relationship的一部分。

您应该考虑在调用函数本身而不是tx中运行这些事务,使用create_relationship或类似函数创建并返回该语句,然后在调用函数中运行这些语句。

获取语句的功能

create_relationship

替换

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

create_relationship(tx, uuid, DERIVED_FROM_REL, parentUUID)
相关问题