Reputation: 867
I'm trying to implement a Cypher Query to select an element inside an Array. This is my csv row:
user_id,name,review_count,friends,useful,funny,cool
ntlvfPzc8eglqvk92iDIAw,Rafael,553,"['oeMvJh94PiGQnx_6GlndPQ', 'wm1z1PaJKvHgSDRKfwhfDg', 'IkRib6Xs91PPW7pon7VVig', 'A8Aq8f0-XvLBcyMk2GJdJQ']",628,225,227
I want to select, for example, friends[0] and find him proprieties. Query will be like this:
MATCH (u:User) WHERE u.name = 'Rafael' RETURN ??u.friends[0], u.friends[1] ..??
Upvotes: 0
Views: 365
Reputation: 66967
If possible, it would be more convenient to change your CSV file's data format for the friends
column to be a semicolon-delimited list (assuming that no list element will ever contain a semicolon or comma), like this:
user_id,name,review_count,friends,useful,funny,cool
ntlvfPzc8eglqvk92iDIAw,Rafael,553,oeMvJh94PiGQnx_6GlndPQ;wm1z1PaJKvHgSDRKfwhfDg;IkRib6Xs91PPW7pon7VVig;A8Aq8f0-XvLBcyMk2GJdJQ,628,225,227
Once that is done, you can import the User
nodes like this:
LOAD CSV WITH HEADERS FROM 'file:///test.csv' AS row
MERGE (u:User {id: row.user_id})
SET u += row{
.name, .useful, .funny, .cool,
review_count: TOINTEGER(row.review_count),
friends: SPLIT(row.friends, ';')
}
RETURN u
And after importing is completed, this query:
MATCH (u:User)
WHERE u.name = 'Rafael'
RETURN u.friends
will return:
╒═════════════════════════════════════════════════════════════════════════════════════════════════════╕
│"u.friends" │
╞═════════════════════════════════════════════════════════════════════════════════════════════════════╡
│["oeMvJh94PiGQnx_6GlndPQ","wm1z1PaJKvHgSDRKfwhfDg","IkRib6Xs91PPW7pon7VVig","A8Aq8f0-XvLBcyMk2GJdJQ"]│
└─────────────────────────────────────────────────────────────────────────────────────────────────────┘
[UPDATE]
If you want to create unique FRIEND
relationships with the friends (instead of creating a friends
property), this should work:
LOAD CSV WITH HEADERS FROM 'file:///test.csv' AS row
MERGE (u:User {id: row.user_id})
SET u += row{
.name, .useful, .funny, .cool,
review_count: TOINTEGER(row.review_count)
}
UNWIND SPLIT(row.friends, ';') AS friendId
MERGE (f:User {id: friendId})
MERGE (u)-[:FRIEND]-(f)
RETURN u
MERGE (u)-[:FRIEND]-(f)
uses an undirected relationship, and will only create the relationship if there is not already one (in either direction).
Upvotes: 1