2014-01-22 48 views
1

我使用neo4j python模块neo4j-embedded来填充neo4j图形。但是我无法弄清楚如何在两个节点之间建立唯一的关系。嵌入式Neo4j Python创建或检查唯一关系

目前我每次都创建一个新的关系,这是绝对不希望的。下面的代码显示了一个简单的例子,我只创建了9个节点,然后将它们与关系“friendsWith”关联起来,但是目前这些关系并不是唯一的,我最终得到了153个关系,但其中大约45个关系是多余的:

from neo4j import GraphDatabase 
neo_db = GraphDatabase('../testdatabase/') 

with neo_db.transaction:               
    person_idx = neo_db.node.indexes.create('people') 
    user_ids = [1,2,3,4,5,6,7,8,9]             

    for user in user_ids: 
    ########################################################################## 
    ## Check if user exists in neo4j,      
    ## If not create it and save id, otherwise find the id.      
    ########################################################################## 
    person_node = person_idx['name'][user].single        
    if person_node == None:              
     person_node = neo_db.node(name=user)          
     person_idx['name'][user] = person_node         

    for friend in user_ids:              
     ########################################################################## 
     ## Check if friend exists in neo4j,        
     ## If not create it and save id, otherwise find the id.      
     ########################################################################## 
     friend_node = person_idx['name'][friend].single       
     if friend_node == None:             
     friend_node = neo_db.node(name=friend)         
     person_idx['name'][friend] = friend_node        
     relationship = person_node.friendsWith(friend_node) 

是否有检查,如果使用上述的Python模块的两个节点之间存在类型的“friendsWith”的关系的任何方式?或者如果 其中一种类型尚不存在,那么这种方式只能创建关系。

我正在寻找一个解决方案,最好不要求使用密码和查询命令查询数据库。

感谢您的任何帮助。


编辑:

我知道你可以使用暗号解决方案如下,但是我正在寻找可以使用的Python来完成,最理想的情况暗号的任何先验知识的一种方式。作为其中的一部分,我并不特别想写一个即席查询功能,我将广泛使用这些功能,只是使用不同的节点和关系。

result = neo_db.query("START n = node:people(name='%i'),m=node:people(name='%i') MATCH (n)-[r:friendsWith]-(m) RETURN r;"%(user,friend)) 
    if result.single == None:             
     relationship = person_node.friendsWith(friend_node) 

回答

1

为什么你不想使用密码?

如果你想避免重复,你必须:

  1. 采用写锁(例如,通过从“锁定”节点中删除一些不存在的属性)
  2. 发现目前所有的双/结束-nodes并把他们/它们的ID为一组结构创建新关系时
  3. 检查针对设置

否则,您必须遍历所有RELS每个创建检查当前到b添加的目标节点已经连接到当前的源节点。

+0

嗨,我不喜欢在这个早期阶段使用密码的主要原因是数据库生成\转换我想保留所有的东西在Python中。我更喜欢在那个环境中工作,如果可能的话,宁愿在python中使用解决方案。 我在建议的解决方案中发现的主要问题是其可伸缩性。这将需要我有一个节点和关系的本地副本。所以我会受到我客户端RAM数量的限制。 本质上,我正在寻找一个python等价的“getOrCreate”关系,如果存在。 – RMcG