在树中,使用 Cypher 计算每个节点与根的距离
In a tree, calculate distance of each node from root, using Cypher
给定这样一棵树
a
/ \
b c
/ \
d e
|
f
我想写一个 Cypher 查询 returns 我:
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}]
(以起点的任何特定顺序)
假设您的关系在树中是定向的 "downwards",并且每个节点都有一个 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}] |
+-------------------------------------------------------------------------------------------+
给定这样一棵树
a
/ \
b c
/ \
d e
|
f
我想写一个 Cypher 查询 returns 我:
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}]
(以起点的任何特定顺序)
假设您的关系在树中是定向的 "downwards",并且每个节点都有一个 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}] |
+-------------------------------------------------------------------------------------------+