2014-11-05 24 views
3

假設我有以下代碼:(py2neo)如何檢查是否存在關係?

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()將是一個函數,要麼添加鏈接2路到數據庫或將其失敗,如果一條路徑已經存在。

在這種情況下,當我撥打link = neo4j.Path(this_node,"friends",friend_node)時,我已經創建了一個this_nodefriend_node之間的路徑,因此link2.create_or_fail(graph_db)應該什麼也不做。這樣的功能可能嗎?

回答

4

我已經爲做的是使用下面的功能:

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()查找與給定的過濾器的關係。

以下link幫助我理解。