2016-11-25 139 views

回答

0

我不確定cypher本身是否可以做到,但是您可以使用編程語言並連接到neo4j來創建節點和關係。
在PHP例如:

function create_children($parent){ 

    print "\n$parent: "; 
    for ($i=0; $i<=7;$i++) { 
     $node_id = (int) "$parent"."$i"; 
     $children[] = $node_id; 
     print "$node_id,"; 
     // create children nodes 
     // CREATE (child:node) SET node_id = $node_id 
     //create relationship here 
     // MATCH (parent:node) where node_id = $parent 
     // CREATE (parent)-[r:parent_of]->(child) 
    } 
    return $children; 

} 


function create_tree ($root, $depth) { 
    if ($depth ==0) return; 
    else{ 
     $children = create_children($root); 
     $depth--; 
     foreach ($children as $child) { 
      create_tree($child, $depth); 
     } 
    } 
} 


// MAIN 

// CREATE (parent:node) SET node_id=0; 
create_tree(0,3); 

當然其中暗號語句是您需要連接到您的Neo4j的實例,並執行這些語句。
如果你不知道怎麼做,你可以只打印出暗號語句,然後將其粘貼到一個新殼或瀏覽器
這裏是運行create_tree(0,2) 的輸出輸出顯示父之後的八個孩子

0: 00,01,02,03,04,05,06,07, 
00: 00,01,02,03,04,05,06,07, 
01: 10,11,12,13,14,15,16,17, 
02: 20,21,22,23,24,25,26,27, 
03: 30,31,32,33,34,35,36,37, 
04: 40,41,42,43,44,45,46,47, 
05: 50,51,52,53,54,55,56,57, 
06: 60,61,62,63,64,65,66,67, 
07: 70,71,72,73,74,75,76,77, 

讓我知道,如果這就是你要找的

1

您可以使用暗號,如果你知道它的提前高度,以產生一棵樹。爲了簡單起見,我生成了二叉樹(分支因子爲2)。

WITH 0 as root, range(1,2) AS branches 
WITH root as root, branches AS l1s, branches AS l2s 
UNWIND l1s AS l1 
UNWIND l2s AS l2 
MERGE (n0:TreeNode {name: root}) 
MERGE (n1:TreeNode {name: l1}) 
MERGE (n2:TreeNode {name: l1+"_"+l2}) 
MERGE (n0)-[:X]->(n1) 
MERGE (n1)-[:X]->(n2) 

這將導致以下三種:

enter image description here

說明:對於k級別的樹,我們複製branches變量K-1次,身心每個列表。這創建了一個笛卡爾積,因此產生了葉節點。對於k級別的(全)二叉樹,這導致2 ^(k-1)個葉節點。 (這也適用於具有8 ^(k-1)級別的八進制)。

我們將級別的數字與下劃線組合起來,爲每個級別創建唯一的變量名稱。這些ID可以查詢這樣:

WITH 0 as root, range(1,2) AS branches 
WITH root as root, branches AS l1s, branches AS l2s 
UNWIND l1s AS l1 
UNWIND l2s AS l2 
RETURN root, l1, l1+"_"+l2 

這導致:

╒════╤═══╤═════════╕ 
│root│l1 │l1+"_"+l2│ 
╞════╪═══╪═════════╡ 
│0 │1 │1_1  │ 
├────┼───┼─────────┤ 
│0 │1 │1_2  │ 
├────┼───┼─────────┤ 
│0 │2 │2_1  │ 
├────┼───┼─────────┤ 
│0 │2 │2_2  │ 
└────┴───┴─────────┘ 

現在我們要做的就是創建節點和關係,同時注意的節點/邊只會創建一次。這通過使用MERGE來保證。 (MERGE似乎在第一靠譜,但也有good explanations。)

如果要添加其他級別,更新查詢這樣:

  • 定義從分支,例如一個新的變量l3s
  • 展開新變量,例如,到l3
  • 爲附加變量名稱的新等級創建附加節點,例如, MERGE (n3:TreeNode {name: l1+"_"+l2+"_"+l3})
  • 從上一級創建新的邊緣,例如,MERGE (n2)-[:X]->(n3)

當然,你也可以使用數字作爲節點。您不需要追加下劃線,而需要爲每個節點生成一個新的數字「ID」。

WITH range(1,2) AS branches 
WITH branches AS l1s, branches AS l2s 
UNWIND l1s AS l1 
UNWIND l2s AS l2 
MERGE (n0:TreeNode {number: 0}) 
MERGE (n1:TreeNode {number: l1}) 
MERGE (n2:TreeNode {number: 2*l1+l2}) 
MERGE (n0)-[:X]->(n1) 
MERGE (n1)-[:X]->(n2) 

結果:

enter image description here

1

您可以通過創建根做的暗號:

CREATE (root:Root:Leaf); 

然後重複查詢添加水平許多倍,因爲你需要(但某些時候交易會變得太大):

MATCH (n:Leaf) 
REMOVE n:Leaf 
FOREACH (i IN range(0, 7) | 
    CREATE (n)-[:CONTAINS]->(:Node:Leaf {value: coalesce(n.value, "") + toString(i)}));