2016-12-29 71 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

沒問題,請在不使用第三方解決方案的情況下帶上您的解決方案。 –

相關問題