Prev |  | Next

## 12.2. Importing data from multiple CSV files

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

Result

Constraints added: 1
`(empty result)`

Query.

    CREATE CONSTRAINT ON (m:Movie) ASSERT m.id IS UNIQUE

Result

Constraints added: 1
`(empty result)`

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]})

Result

Nodes created: 2
Properties set: 4
Labels added: 2
`(empty result)`

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]})

Result

Nodes created: 5
Properties set: 10
Labels added: 5
`(empty result)`

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)

Result

`(empty result)`

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

Result

Constraints removed: 1
`(empty result)`

Query.

    DROP CONSTRAINT ON (m:Movie) ASSERT m.id IS UNIQUE

Result

Constraints removed: 1
`(empty result)`

Query.

    MATCH (n)
    REMOVE n.id

Result

Properties set: 7
`(empty result)`

Copyright © 2014 Neo Technology

Prev | Up | Next
| Home |