获取节点之间的关系

时间:2017-05-29 08:28:21

标签: graph neo4j spring-data-neo4j

我使用此查询获得以下类型的图表:

MATCH (p:Person)-[:REPORTS_TO *]->(c:Person) WHERE p.name="F"
WITH COLLECT (c) + p AS all 
UNWIND all as p MATCH (p)-[:REPORTS_TO]-(c) 
RETURN p,c;

enter image description here

使用情况:

1。我想找到与节点F相关的节点级别? 示例:

    Node `D`, `E` are direct child of `F`, hence they are at level 1

    Node `A,B,C` are childs of `D` (which is child of `F`) hence level 2

    Node `X` is child of `A' (which is at level 2), hence level 3

and so onnnnn....

我尝试通过引入变量i来解决这个问题,并在每次迭代时递增它(但它没有工作)。

MATCH (p:Person)-[:REPORTS_TO *]->(c:Person) WHERE p.name="F"
WITH COLLECT (c) + p AS all ,i:int=0
UNWIND all as p MATCH (p)-[:REPORTS_TO]->(c) 
RETURN p,c, i=i+1;

2。给定两个节点之间的关系

例如Find relation between F and X?

预期answer = 3 (as it is at level 3)

我应该如何解决这些用例?

注意: Neo4j服务器的图形响应不是必需的,Json响应也没问题。

1 个答案:

答案 0 :(得分:2)

UC1使用Pathlength(p)功能

MATCH p=(root:Person)-[:REPORTS_TO *]->(child:Person) 
WHERE root.name="F"
RETURN nodes(p)[-2], nodes(p)[-1],length(p)

这将从根节点找到所有路径,并返回所需的倒数第二个到最后一个节点和最后一个节点+对。

节点(p) - 路径p上的节点列表

[ - 2] - 列表末尾的第二个节点

UC2:使用shortestPath功能:

MATCH (p1:Person),(p2:Person)
WHERE p1.name = '..' AND p2.name = '...'
MATCH p=shortestPath((p2)-[:REPORTS_TO*]->(p2))
RETURN length(p)