我正在使用 neo4j python 模块 neo4j-embedded填充 neo4j 图表。但是我不知道如何在两个节点之间建立唯一的关系。
目前我每次都会创建一个新的关系,这绝对是不希望的。下面的代码显示了一个简单的示例,我只是创建 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”类型的关系?或者一种仅在以下情况下建立关系的方法: 该类型之一尚不存在。
我正在寻找一种最好不需要使用 cypher 和查询命令查询数据库的解决方案。
感谢您的帮助。
<小时/>编辑:
我意识到您可以使用 cypher 获得解决方案,如下所示,但是我正在寻找一种仅使用 python 即可完成的方法,理想情况下不需要任何 cypher 的先验知识。其中一部分是,我并不特别希望为我将广泛使用的功能编写一个临时查询,只是针对不同的节点和关系。
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)
最佳答案
为什么你不想使用密码?
如果你想避免重复,你必须:
- 获取写入锁定(例如,通过从“锁定”节点中删除某些不存在的属性)
- 找到所有当前对/端节点并将它们/它们的 id 放入集合结构中
- 创建新关系时,请检查该组关系
否则,您必须在每次创建时迭代所有rel,以检查当前要添加的目标节点是否已连接到当前源节点。
关于python - 嵌入式 Neo4j Python 创建或检查唯一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21273772/