Keith Lyons
Keith Lyons

Reputation: 624

Neo4j - Create relationship within label on property

I'm importing a dataset of the following structure into Neo4j:

|     teacher     | student | period |
|:---------------:|---------|:------:|
| Mr. Smith       | Michael | 1      |
| Mrs. Oliver     | Michael | 2      |
| Mrs. Roth       | Michael | 3      |
| Mrs. Oliver     | Michael | 4      |
| Mrs. Oliver     | Susan   | 1      |
| Mrs. Roth       | Susan   | 2      |

My goal is to create a graph where a teacher "sends" students from one period to the next, showing the flow of students between teachers. The above graph for instance, would look like this:

teacher_graph

Using words, my logic looks like this:

  1. Generate a unique node for every teacher
  2. For each student, create a relationship connecting the earliest period to the next earliest period, until the latest period is reached.

My code so far completes the first step:

LOAD CSV WITH HEADERS FROM 'file:///neo_sample.csv' AS row // loads local file
MERGE(a:teacher {teacher: row.teacher}) // used merge instead of create to produce unique teacher nodes.

Upvotes: 0

Views: 134

Answers (1)

cybersam
cybersam

Reputation: 67044

Here is how you can produce your illustrated graph.

Assuming your CSV file looks like this:

teacher;student;period
Mr. Smith;Michael;1
Mrs. Oliver;Michael;2
Mrs. Roth;Michael;3
Mrs. Oliver;Michael;4
Mrs. Oliver;Susan;1
Mrs. Roth;Susan;2

then this query should work:

LOAD CSV WITH HEADERS FROM 'file:///neo_sample.csv' AS row FIELDTERMINATOR ';'
WITH row.teacher AS t, row.student AS s, row.period AS p
ORDER BY p
WITH s, COLLECT({t:t, p:p}) AS data
FOREACH(i IN RANGE(0, SIZE(data)-2) |
  MERGE(a:Teacher {name: data[i].t})
  MERGE(b:Teacher {name: data[i+1].t})
  MERGE (a)-[:SENDS {student: s, period: data[i].p}]->(b)
)

Upvotes: 1

Related Questions