Loading relationships from CSV data into neo4j db

浪尽此生 提交于 2019-12-11 03:45:29

问题


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)


回答1:


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))
...


来源:https://stackoverflow.com/questions/28599231/loading-relationships-from-csv-data-into-neo4j-db

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!