(py2neo) 如何检查关系是否存在?

3
假设我有以下代码:
    link = neo4j.Path(this_node,"friends",friend_node) #create a link between 2 nodes
    link.create(graph_db) #add the link aka the 'path' to the database

但是假设稍后我打电话过来:
link2 = neo4j.Path(friend_node,"friends",this_node)
link2.create_or_fail(graph_db)

基本上,link.create_or_fail() 是一种函数,它要么将 link2 路径添加到数据库中,要么如果路径已经存在则失败。

在这种情况下,当我调用 link = neo4j.Path(this_node,"friends",friend_node) 时,我已经在 this_nodefriend_node 之间创建了一条路径,所以 link2.create_or_fail(graph_db) 不应该做任何事情。这样的功能是否可能?

2个回答

5
我使用了以下函数来完成这项工作:
def create_or_fail(graph_db, start_node, end_node, relationship):
    if len(list(graph_db.match(start_node=start_node, end_node=end_node, rel_type=relationship))) > 0:
        print "Relationship already exists"
        return None
    return graph_db.create((start_node, relationship, end_node))

方法graph_db.match()用于查找具有给定筛选条件的关系。
我通过以下链接理解了这一点。

0
如果您正在寻找更新版本的py2neo,则可以调用match_one检查关系: graph.match(nodes = nodeList, r_type = rtype) 其中,nodeList是关系的节点序列,rtype是关系类型。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接