加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

nosql – neo4j:单向/双向关系?

发布时间:2020-12-13 13:30:41 所属栏目:百科 来源:网络整理
导读:所以我研究了neo4j,我可能会在即将到来的项目中使用它,因为它的数据模型可能非常适合我的项目.我看过文档,但我仍然需要回答这个问题: 我可以将关系设为单向吗? 似乎neo4j人喜欢电影,所以让我们继续吧.如果我有这样的图形: Actor A - [:Acts in] - Movie B
所以我研究了neo4j,我可能会在即将到来的项目中使用它,因为它的数据模型可能非常适合我的项目.我看过文档,但我仍然需要回答这个问题:

我可以将关系设为单向吗?

似乎neo4j人喜欢电影,所以让我们继续吧.如果我有这样的图形:

Actor A -> [:Acts in] -> Movie B

那么方向是明显的,因为节点是不同的类型.

但我喜欢恐怖电影,所以…

Person A -> [:wants_to_kill] -> Person B

我需要这种关系才是一个方向的,所以如果我查询“谁要杀人?”我得到人B,如果我查询“人B想杀人?”我什么都没有

有时我仍然需要关系来做两个方向

喜欢:

Person A <-[:has_met] -> Person B

…这很明显

文件说:

Relationships are equally well traversed in either direction. This means that there is
no need to add duplicate relationships in the opposite direction (with regard to 
traversal or performance).

While relationships always have a direction,you can ignore the direction where it is 
not useful in your application.

所以docs说,默认情况下的关系有一个方向,如果我愿意,我可以忽略.

现在这就是复杂的事情:

考虑下面的图表(注意箭头)

Person A <- [:wants_to_kill] -> Person B
Person B -> [:wants_to_kill] -> Person C
Person C -> [:wants_to_kill] -> Person A

如果我忽略所有的方向[:wanted_to_kill],我会得到错误的结果
为“谁想杀人?
如果我知道我不得不忽略哪些,我不会做这个查询.

那么我可以以某种方式将关系设置为双向的(创建它们时),还是应该用两种关系(人与人之间)之间建立关系?

Neo4j的关系总是有一个方向.如果关系类型的语义不包含方向,例如has_met从你的例子,那么最好的做法是应用任意方向创建关系.然后通过使用“双向”(没有“更大/小于”字符)来完成查询,在cypher中:
start ... match (a)-[:HAS_MET]-(b) ....

相反,如果一个关系的语义确实有一个像你想要的方向,你需要使用两个关系来表示a和b要杀死另一个,反之亦然.对于上面的示例,您需要有4个关系:

Person A -[:wants_to_kill]-> Person B
Person B -[:wants_to_kill]-> Person A
Person B -[:wants_to_kill]-> Person C
Person C -[:wants_to_kill]-> Person A

要找到A想杀死你的所有人:

start a=node:node_auto_index(name='A') match a-[:wants_to_kill]->victims_of_a return victims_of_a

找到所有想要杀死A的人:

start a=node:node_auto_index(name='A') match murderer_of_a-[:wants_to_kill]->a return murderer_of_a

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读