2016-11-25 135 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)}));