从Neo4j中检索分层数据

时间:2016-04-07 12:22:59

标签: neo4j cypher

TL; DR:我有一个树形图,我想要一个Cypher查询,它将返回该树。

考虑以下图表:

CREATE (a:Group {name:"Alpha"}),
       (b:Group {name:"Bravo"}),
       (c:Group {name:"Charlie"}),
       (d:Group {name:"Delta"}),
       (e:Group {name:"Echo"}),
       (f:Group {name:"Foxtrot"}),
       (a)<-[:MEMBER_OF]-(b),
       (b)<-[:MEMBER_OF]-(c),
       (b)<-[:MEMBER_OF]-(d),
       (d)<-[:MEMBER_OF]-(e),
       (a)<-[:MEMBER_OF]-(f);

Image of Graph with Hierarchical Node Arrangement

    A
   / \
  B   F
 / \
C   D
    |
    E

我想要的是一个包含该图的关联数组:

[
    Alpha => [
        Bravo   [
            Charlie,
            Delta [
                Echo
            ]
        ],
        Foxtrot
    ]
]

最接近我想要的最简单的解决方案是:

MATCH p=(:Group{name:"Alpha"})<-[:MEMBER_OF*]-(g:Group)
WITH nodes(p) AS groups
RETURN groups;

..返回五(5)行:

[{name:"Alpha"},{name:"Bravo"}]
[{name:"Alpha"},{name:"Bravo"},{name:"Charlie"}]
[{name:"Alpha"},{name:"Bravo"},{name:"Delta"}]
[{name:"Alpha"},{name:"Bravo"},{name:"Delta"},{name:"Echo"}]
[{name:"Alpha"},{name:"Foxtrot"}]

我能够使用聚合函数使事情更接近,但是这些函数与它们有一些奇怪的行为,更重要的是,它们一次只能作用于一个“级别”(并且不能嵌套)。

MATCH p=(:Group{name:"Alpha"})<-[:MEMBER_OF*]-(g:Group)
WITH nodes(p) AS groups
RETURN head(groups), collect(tail(groups));

..使用WITH甚至更多我可以获得树的下一个'级别'但是事情变得非常混乱匆忙这种方法只有在我知道有多少'级别'到我的树时我才会工作在正常情况下。

0 个答案:

没有答案