jos*_*011 12 relationship neo4j nosql
所以我研究了neo4j,我可能会在即将到来的项目中使用它,因为它的数据模型可能非常适合我的项目.我查看了文档,但我仍然需要回答这个问题:
我可以将关系设置为单向的吗?
似乎neo4j人喜欢电影所以让我们继续这样做.如果我有这样的图表:
Actor A -> [:Acts in] -> Movie B
Run Code Online (Sandbox Code Playgroud)
那么方向是显而易见的,因为节点是不同的类型.
但我喜欢恐怖电影......
Person A -> [:wants_to_kill] -> Person B
Run Code Online (Sandbox Code Playgroud)
我需要这种关系是单向的,所以如果我查询"人A想杀谁?" 我得到人B,如果我查询"B人想杀谁?" 我一无所获.
有时我仍然需要关系是双向的
喜欢:
Person A <-[:has_met] -> Person B
Run Code Online (Sandbox Code Playgroud)
......很明显.
文件说:
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.
Run Code Online (Sandbox Code Playgroud)
所以文档说,默认关系有一个方向,如果我愿意,我可以忽略它.
现在这是事情变得复杂的地方:
考虑下面的图表(并注意箭头)
Person A <- [:wants_to_kill] -> Person B
Person B -> [:wants_to_kill] -> Person C
Person C -> [:wants_to_kill] -> Person A
Run Code Online (Sandbox Code Playgroud)
如果我忽略了所有的方向,[:wants_to_kill]我得到的错误结果是"人员A/C想杀谁?" 如果我知道哪些我必须忽略,我就不会进行查询.
那么我能以某种方式将关系设置为双向(创建它们时),还是应该用两种关系(人员A和B之间)建立关系?
Ste*_*ter 34
Neo4j中的关系始终有一个方向.如果关系类型的语义不包含方向,例如has_met来自您的示例,则最佳实践是在创建关系时应用任意方向.然后通过使用密码中的"双向"(没有"大于/小于"字符)符号来完成查询:
start ... match (a)-[:HAS_MET]-(b) ....
Run Code Online (Sandbox Code Playgroud)
相反,如果关系的语义确实有像你这样的方向wants_to_kill,你需要使用两个关系来表示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
Run Code Online (Sandbox Code Playgroud)
要找到A想要杀死的所有人,你可以:
start a=node:node_auto_index(name='A') match a-[:wants_to_kill]->victims_of_a return victims_of_a
Run Code Online (Sandbox Code Playgroud)
找到所有想要杀死A的人:
start a=node:node_auto_index(name='A') match murderer_of_a-[:wants_to_kill]->a return murderer_of_a
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5420 次 |
| 最近记录: |