给出以下图表:
可通过以下Cypher脚本创建:
CREATE
(n1:Token {content: "lonely"}),
(n2:Token {content: "island"}),
(n1)-[:PRECEDES]->(n2);
CREATE
(n1:Token {content: "the"}),
(n2:Token {content: "quick"}),
(n3:Token {content: "brown"}),
(n4:Token {content: "fox"}),
(n5:Token {content: "bear"}),
(n1)-[:PRECEDES]->(n2),
(n2)-[:PRECEDES]->(n3),
(n3)-[:PRECEDES]->(n4),
(n3)-[:PRECEDES]->(n5);
我想要一个查询,它将返回来自给定根目录的路径中的节点 PRECEDES关系倒退。查询应该也全部返回 给定节点的传入关系,以便我可以构造子图 在内存中以后。但是,传入关系列表永远不应该指向 在返回的根之外。
例如,如果我查询根lonely
,我想要结果:
+-----------------------------------------------------------------------+
| (:Token {content: "lonely"}) | [] |
| (:Token {content: "island"}) | [[:PRECEDES]] |
+-----------------------------------------------------------------------+
如果我查询根the
,我想要结果:
+-----------------------------------------------------------------------+
| (:Token {content: "the"}) | [] |
| (:Token {content: "quick"}) | [[:PRECEDES]] |
| (:Token {content: "brown"}) | [[:PRECEDES]] |
| (:Token {content: "fox"}) | [[:PRECEDES]] |
| (:Token {content: "bear"}) | [[:PRECEDES]] |
+-----------------------------------------------------------------------+
如果我查询根brown
,我想要以下结果,请注意
brown
本身的传入关系已被省略,因为它会
点在子图之外。
+-----------------------------------------------------------------------+
| (:Token {content: "brown"}) | [] |
| (:Token {content: "fox"}) | [[:PRECEDES]] |
| (:Token {content: "bear"}) | [[:PRECEDES]] |
+-----------------------------------------------------------------------+
根节点和叶节点应始终包含在结果中。
这是我到目前为止的尝试:
MATCH (a:Token {content: {root}})-[:PRECEDES*]->(t:Token)
WITH COLLECT(a) + COLLECT(DISTINCT t) AS nodes_
UNWIND nodes_ AS n
OPTIONAL MATCH p = (n)-[r]-()
WITH n AS n2, COLLECT(DISTINCT RELATIONSHIPS(p)) AS nestedrel
RETURN n2, REDUCE(output = [], rel in nestedrel | output + rel) AS rels
这种情况很接近但有几个问题:使用COLLECT(a)
人为地包括根是一种hacky,它留下了关系
在关系结果中指向远离根,并且如果您尝试使用a
叶节点作为根它赢得了根本不返回任何节点。 (REDUCE
部分是
只需将关系列表展平一级。)
[仅供参考,我需要在内存中重建这个树结构作为 NetworkX MultiDiGraph。]