This tutorial will show you how to import data from multiple CSV files using LOAD CSV.
These files might be the result of exporting tables from a relational database and might
contain explicit join keys.
In this example, we’ll use three files, one listing people, one listing movies and another one describing which movies have been directed by whom. All the rows in movies.csv and persons.csv will have an explicit primary key as you may expect in a relational database. The directors.csv mapping will consists of pairs of said keys.
We’ll use the following steps to import those three CSV files to the graph.
Initially, we’ll create indices for the id property on Person and Movie nodes. The id property
will be a temporary property used to look up the appropriate nodes for a relationship when
importing the third file. By creating an index, the MATCH look ups will be much faster.
Query.
CREATE CONSTRAINT ON (p:Person) ASSERT p.id IS UNIQUE
Query.
CREATE CONSTRAINT ON (m:Movie) ASSERT m.id IS UNIQUE
First, we import the movies.csv file and create a Movie node for each row.
Query.
LOAD CSV FROM
"file:/jenkins/workspace/neo4j-2.1-release-candidate/target/community/cypher/cypher-docs/target/docs/dev/ql/import/csv-files/movies.csv"
AS csvLine
CREATE (m:Movie { id: toInt(csvLine[0]), title: csvLine[1]})
Second, we do the same for the persons.csv file.
Query.
LOAD CSV FROM
"file:/jenkins/workspace/neo4j-2.1-release-candidate/target/community/cypher/cypher-docs/target/docs/dev/ql/import/csv-files/persons.csv"
AS csvLine
CREATE (p:Person { id: toInt(csvLine[0]), name: csvLine[1]})
The last step is to create the relationships between nodes we’ve just created. Given a
pair of two IDs, we look up the corresponding nodes and create a DIRECTED relationship
between them.
Query.
LOAD CSV FROM
"file:/jenkins/workspace/neo4j-2.1-release-candidate/target/community/cypher/cypher-docs/target/docs/dev/ql/import/csv-files/directors.csv"
AS csvLine
MATCH (p:Person { id: toInt(csvLine[0])}),(m:Movie { id: csvLine[1]})
CREATE (p)-[:DIRECTED]->(m)
Finally, as the id property was only necessary to import the relationships, we can drop the constraints and the property from all nodes.
Query.
DROP CONSTRAINT ON (p:Person) ASSERT p.id IS UNIQUE
Query.
DROP CONSTRAINT ON (m:Movie) ASSERT m.id IS UNIQUE
Query.
MATCH (n) REMOVE n.id
Copyright © 2014 Neo Technology