Import csv and create relations between product nodes

I need some help matching data from csv to create relations. I've a csv of all products and a csv containing products that are often bought together.
I've made nodes based on this csv:

_p0umd0,Garlic (Lehsan)

now my other csv contains items that re frequently bought together in a single row, as follows:


Now I want to create relations for above created nodes using this csv, where all products in a row have a relation with each other, but I can't figure out how to do it.

Below is the code I tried:

LOAD CSV WITH HEADERS FROM "file:///product_assocations.csv" as csv
MATCH (p0:Product {slug:csv.product_0}), (p1:Product {slug:csv.product_1}), (p2:Product {slug:csv.product_2}), (p3:Product {slug:csv.product_3}), (p4:Product {slug:csv.product_4}), (p5:Product {slug:csv.product_5})
MERGE (p0)-[:BOUGHT_WITH]->(p1)-[:BOUGHT_WITH]->(p2)-[:BOUGHT_WITH]->(p3)-[:BOUGHT_WITH]->(p4)-[:BOUGHT_WITH]->(p5)

I've stored nodes in [:Product] field and they are visible there.

Can someone please help me out with making connections. I'm totally new to neo4j and can't seem to figure it out.

I updated the query like this but it just creates a small no of relations:

LOAD CSV WITH HEADERS FROM "file:///product_assocations.csv" as csv
MATCH (p0:Product { slug: csv.product_0})
MATCH (p1:Product { slug: csv.product_1})
MATCH (p2:Product { slug: csv.product_2})
MATCH (p3:Product { slug: csv.product_3})
MATCH (p4:Product { slug: csv.product_4})
MATCH (p5:Product { slug: csv.product_5})

The result is:

It created only 10 relations, while I've about 700 relations in my file (as rows)


Looks like you are assuming every row has 5 products. You logic should consider the fact sometimes you just have 2 elements in a row.


So should I make seprate logic for all types of connections. There can be anywhere between 2 to 6 items per row.

Hi @hamzaalijoiyah ,

I added another column named receipt in order to handle an id of the purchase. you wil need it for sure.

LOAD CSV WITH HEADERS FROM "file:///product_assocations.csv" as csv
with csv.reciept as recId, [k in keys(csv) where k <> 'reciept' and csv[k] is not null| csv[k] ] as vals
UNWIND vals as val
MERGE(p:Product {ID : val})
with recId, collect(p) as nodes
unwind nodes as p0
unwind nodes as p1
with recId, p0, p1
where id(p0)<id(p1)
MERGE (p0)-[:BOUGHT_TOGETHER{receipt : recId}]->(p1)

Lemme know if it works


No it didnot. It is not taking into account the slug and product names of products(stored in another csv). I want a way to create nodes containing information in 1st csv and then use the 2nd csv to make relations between these nodes. Is there a way to do that? Thanks a lot for your help.


Create Products first. Then add an index on :Product(ID). Last with your second csv, execute the query shared previously.