使用py2neo删除特定关系

时间:2016-05-30 11:02:33

标签: python neo4j cypher py2neo

我们说我们有2个节点,User和Post。这种关系,比如upvote,可以作为(:用户) - [UPVOTED] - >(:Post)存在

如果以下查询导致非空列表,那么我希望删除关系:

        rel_list = list(graph.match(start_node=user, end_node=post, rel_type="UPVOTED")
        if len(rel_list) > 0:
            # delete the relationship from the graph
        else:
            # create the relationship
            rel = Relationship(user, "UPVOTED", post)
            graph.create_unique(rel)

2 个答案:

答案 0 :(得分:0)

要删除关系,您应使用separate方法:http://py2neo.org/v3/database.html#py2neo.database.Transaction.separate

您可能希望在GitHub中查看此问题,以便进行一些讨论:https://github.com/nigelsmall/py2neo/issues/508

此致

答案 1 :(得分:0)

回答我自己的问题,希望这也有助于其他人。

    rel_list = list(graph.match(start_node=user, end_node=post, rel_type="UPVOTED")
    if len(rel_list) > 0:
        # delete the relationship from the graph
        # fetch the ID of the relationship -> rel_id
        query = '''
        MATCH (a:NeoZotr)-[r:LIKED]->(b:NeoZot)
        WHERE ID(r) = {x}
        DELETE r
        '''
        graph.cypher.execute(query,x=rel_id)
    else:
        # create the relationship
        rel = Relationship(user, "UPVOTED", post)
        graph.create_unique(rel)

如果您最终遇到TypeError(就像我的情况一样),那么您获取的rel_id可能是unicode样式。在这种情况下传递int(rel_id)。