I want to the following data to a neo4j database. The column "friends" is a string of ids separated by ",". So, there should be 10 nodes (id of 1-10) where only 5 of them I know about their ages. And I want to have relationship between each id and their friends.
Example dataframe
id age friends
1 10 "3,2"
2 20 "1,6"
3 15 "4,5,10"
4 13 "2,8,9"
5 25 "1,4,7"
My code using is
LOAD CSV WITH HEADERS FROM 'file:///df.csv' AS line
MERGE (User {id: line.id, age: line.age})
LOAD CSV WITH HEADERS FROM 'file:///df.csv' AS line
UNWIND split(line.friends, ',') AS friends
MERGE (u:User {id: friends})
LOAD CSV WITH HEADERS FROM 'file:///df.csv' AS line
UNWIND split(line.friends, ',') AS friends
With line, friends
MERGE (User1{id: line.id})-[:FRIENDS]->(User2{id: friends})
Is it the correct way to do it? And how to simplify the code?
A foreach
should do it:
LOAD CSV WITH HEADERS FROM 'file:///df.csv' AS line
MERGE (u:User {id: line.id}) SET u.age=toInteger(line.age)
WITH u,line,split(line.friends, ',') AS friends
FOREACH (f in friends | merge (friend:User {id: f}) merge (u)-[:FRIENDS]->(friend))
All values are Strings, so you will need to convert to other data types if required (see age).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.