changingrainbows
changingrainbows

Reputation: 2711

Loading relationships from CSV data into neo4j db

Neo4j 2.1.7

Attempting to mass-connect a bunch of nodes via information I've received in a CSV, which looks like:

person_id,book_id,relationship
111,AAA,OWNS
222,BBB,BORROWS
333,AAA,BORROWS

The nodes :Person and :Book used in this CSV were successfully loaded via LOAD CSV and CREATE statements, and already exist in the database. Now, I'd like to load this above CSV of relationships between :Person and :Book. The relationships are defined in the CSV itself.

LOAD CSV WITH HEADERS FROM "file:data.csv" AS row
MATCH (person:Person { personID: row.person_id })
MATCH (book:Book { bookID: row.book_id })

Sure, the next MERGE command works if I supply a specific name ([:OWNS], [:BORROWS], etc.) but as you can see, my relationships are supplied by the incoming data.

However, I'd like the relationship defined in MERGE to not be a "hard-coded" string, but come as data from the 3rd column of my CSV instead. Something along the lines of:

MERGE (person)-[row.relationship]->(book)

Is this even possible?

PS: I've tried the syntax above, and also -[:row.relationship]->, both to no avail (syntax errors)

Upvotes: 2

Views: 459

Answers (1)

Dave Bennett
Dave Bennett

Reputation: 11216

I don't think it is possible with LOAD CSV. You need to do a little trickery with the input data and collections. If the relationship in the input csv contains OWNS create a collection with a one in it otherwise create an empty collection. Do the same for the BORROWS relationship value. It will be something like this...

...
case when row.relationship = "OWNS" then [1] else [] end as owns
case when row.relationship = "BORROWS" then [1] else [] end as borrows
foreach(x in owns | MERGE (person)-[:OWNS]->(book))
foreach(x in borrows | MERGE (person)-[:BORROWS]->(book))
...

Upvotes: 2

Related Questions