2016-12-29 121 views
1

我有我的数据库中共有10个节点Neo4j的:获取顶级节点与他们的孩子一起

M1 -> M2 -> M4 -> M5 
M1 -> M3 
M6 
M7 -> M8 
M7 -> M9 
M7 -> M10 

我需要火查询应该返回我造成像,因为它是以下JSON可以使用在客户端应用程序中显示树结构(没有任何额外的处理)(总根级记录3,但所有子节点都依赖于关系嵌套)。

[ 
    { 
    "name": "M1", 
    "child": [ 
     { 
     "name": "M2", 
     "child": [ 
      { 
      "name": "M4", 
      "child": [ 
       { 
       "name": "M5" 
       } 
      ] 
      } 
     ] 
     }, 
     { 
     "name": "M3" 
     } 
    ] 
    }, 
    { 
    "name": "M6" 
    }, 
    { 
    "name": "M7", 
    "child": [ 
     { 
     "name": "M8", 
     }, 
     { 
     "name": "M9" 
     }, 
     { 
     "name": "M10" 
     } 
    ] 
    } 
] 

是类似的东西可能与Neo4j的(当调用从Java代码,查询它应该得到节点的嵌套集合)

回答

0

您可以从APOC使用apoc.convert.toTree。例如,在下面的初始数据:

MERGE (M1:TREE {name:'m1'}) MERGE (M2:TREE {name:'m2'}) 
MERGE (M3:TREE {name:'m3'}) MERGE (M4:TREE {name:'m4'}) 
MERGE (M5:TREE {name:'m5'}) MERGE (M6:TREE {name:'m6'}) 
MERGE (M7:TREE {name:'m7'}) MERGE (M8:TREE {name:'m8'}) 
MERGE (M9:TREE {name:'m9'}) MERGE (M10:TREE {name:'m10'}) 
MERGE (M1)-[:hasChild]->(M2) MERGE (M2)-[:hasChild]->(M4) 
MERGE (M4)-[:hasChild]->(M5) MERGE (M1)-[:hasChild]->(M3) 
MERGE (M7)-[:hasChild]->(M8) MERGE (M7)-[:hasChild]->(M9) 
MERGE (M7)-[:hasChild]->(M10) 

查询可以如下:

// Get leaf 
MATCH (T:TREE) WHERE NOT (T)-[:hasChild]->(:TREE) WITH T 
// Get branches 
OPTIONAL MATCH path = (P:TREE)-[:hasChild*0..]->(T) WHERE NOT (P)<-[:hasChild]-() 
WITH collect(path) as paths 
// Convert paths to tree 
CALL apoc.convert.toTree(paths) YIELD value 
RETURN value as tree 
+0

我实在不明白的基础上某人的第三方解决方案/框架的答案值。 –

+0

没问题,请在不使用第三方解决方案的情况下带上您的解决方案。 –

相关问题