在树中,使用Cypher计算每个节点与根的距离

时间:2016-05-11 14:25:39

标签: neo4j tree cypher

给出这样的树

     a
    / \
   b   c
  / \
 d   e
 |
 f

我想编写一个返回我的Cypher查询:

startPoint: f, endPoint: a, path: [{f,3},{d,2},{b,1},{a,0}]
startPoint: d, endPoint: a, path: [{d,2},{b,1},{a,0}]
startPoint: e, endPoint: a, path: [{e,2},{b,1},{a,0}]
startPoint: b, endPoint: a, path: [{b,1},{a,0}]
startPoint: c, endPoint: a, path: [{c,1},{a,0}]

(以startPoint的任何特定顺序)

1 个答案:

答案 0 :(得分:1)

假设您的关系是指向"向下"在树中,每个节点都有id属性,这应该有效:

MATCH p=(a)<-[*]-(b {id:'a'})
WITH a, b, NODES(p) AS pts, LENGTH(p) AS n
RETURN
  a.id AS startPoint,
  b.id AS endPoint,
  REDUCE(s = [], i IN RANGE(0, n) | s + {id: (pts[i]).id, depth: n-i}) AS path;

以下是示例输出:

+-------------------------------------------------------------------------------------------+
| startPoint | endPoint | path                                                              |
+-------------------------------------------------------------------------------------------+
| "b"        | "a"      | [{id=b, depth=1},{id=a, depth=0}]                                 |
| "d"        | "a"      | [{id=d, depth=2},{id=b, depth=1},{id=a, depth=0}]                 |
| "f"        | "a"      | [{id=f, depth=3},{id=d, depth=2},{id=b, depth=1},{id=a, depth=0}] |
| "e"        | "a"      | [{id=e, depth=2},{id=b, depth=1},{id=a, depth=0}]                 |
| "c"        | "a"      | [{id=c, depth=1},{id=a, depth=0}]                                 |
+-------------------------------------------------------------------------------------------+