如何基于父节点在两个随机节点之间创建关系?

时间:2017-01-12 14:42:24

标签: neo4j

我正在为我的公司开发一个PoC,以努力转向图形数据库,以利用使用图形数据库的一些关系分析优势。

我创建了一个数据集如下:

foreach (x in range(1,1400) | create (:District {name: "District " + x, id: "district-" + x}))
foreach (x in range(1,10000) | create (:School {name: "School " + x, id: "school-" + x}))
foreach (x in range(1,50000) | create (:Teacher {name: "Teacher " + x, id: "teacher-" + x}))
foreach (x in range(1,50000) | create (:Class {name: "Class " + x, id: "class-" + x}))

我已经开始与这些查询建立基本关系:

创建学校 - >区

match (s: School)
match (d: District)
with collect (distinct s) as school, collect (distinct d) as districts

foreach (school in schools |
    foreach (district in [districts[toInteger(rand()*size(districts))]] |
        create unique (school)-[:belongs_to]->(district)
        )
    )

创建类 - >校

match (c:Class)
match (s:School)
with collect (distinct c) as classes, collect (distinct s) as schools

foreach (class in classes |
    foreach (school in [schools[toInteger(rand()*size(schools))]] |
        create unique (class)<-[:has]-(school)
        )
    )

创建教师 - &gt;校

match (t:Teacher)
match (s:School)
with collect (distinct t) as teachers, collect (distinct s) as schools

foreach (teacher in teachers |
    foreach (school in [schools[toInteger(rand()*size(schools))]] |
        create unique (teacher)-[:teachers_at]->(school)
        )
    )

我目前面临的问题是:我需要让每位教师随机分配给0-2课程,但仅适用于教师所教学校的课程。我已经尝试在MATCH块中放置FOREACH语句,但这违反了Cypher查询的规则。

我正在寻找有关创建此特定查询的建议。

  

注意:顺便说一句,我将不得不为一组250,000名学生再次完成这个过程(随机分配到一所学校,然后随机分配到0-4班)。

1 个答案:

答案 0 :(得分:0)

您可以选择从教师到学校的模式。然后从学校到班级。然后随机排序类,然后使用限制:

MATCH (teacher:Teacher) WITH teacher
MATCH (teacher)-[:teachers_at]->(:School)-[:has]->(class:Class)
WITH teacher, 
     class ORDER BY RAND()
WITH teacher, 
     collect(class)[0..toInteger(rand()*3)] as classes
UNWIND classes as class
CREATE (teacher)-[:has_class]->(class)