How to make relationship between csv columns in neo4j?

Viewed 133

I have three csv files:

sample_users.csv

user_id, first_name, location

sample_orders.csv

order_id, user_id, product,order_ts

sample_products.csv

product_id, product

I was successful in making relationship between sample_users with sample_orders but now I want to get the product_id of each product ordered in the sample_orders table. but I am failing in that. There is no error but the relationship is not happening. What is going wrong?

//load user nodes
LOAD CSV WITH HEADERS FROM 'file:///sample_users.csv' AS row 
MERGE(u:User {user_id:row.user_id, name:row.first_name, location:row.location})
RETURN count(u);

//load order nodes
LOAD CSV WITH HEADERS FROM 'file:///sample_orders.csv' AS row WITH row WHERE row.order_id IS NOT NULL 
MERGE(o:Orders {order_id:row.order_id, order_ts:row.order_ts, user_id_2:row.user_id, product:row.product})
RETURN count(o);

//load product nodes
LOAD CSV WITH HEADERS FROM 'file:///sample_products_v2.csv' AS row WITH row where row.p_name IS NOT NULL
MERGE(p:Products {product_id:row.p_id, product_name:row.p_name})
RETURN count(p);

//Create relationships 
LOAD CSV WITH HEADERS FROM 'file:///sample_users.csv' AS row 
MATCH(u:User{user_id:row.user_id})
MATCH(o:Orders{user_id_2:row.user_id})
MERGE(u)-[:HAS_ORDERED]->(o)
RETURN *;

LOAD CSV WITH HEADERS FROM 'file:///sample_products_v2.csv' AS row
MATCH(o:Orders{product:row.product})
MATCH(p:Products{product_name:row.p_name})
MERGE(p)-[:IS_ITEM]->(o)
RETURN *;
1 Answers

There is a typographical error on your script. Your column names for Products are product_id, product.

This should be the loading script:

//load product nodes
LOAD CSV WITH HEADERS FROM 'file:///sample_products.csv' AS row WITH row where row.product IS NOT NULL
MERGE(p:Products {product_id:row.product_id, product_name:row.product})
RETURN count(p);

Thus you should use

LOAD CSV WITH HEADERS FROM 'file:///sample_products.csv' AS row
MATCH(o:Orders{product:row.product_id})
MATCH(p:Products{product_name:row.product})
MERGE(p)-[:IS_ITEM]->(o)
RETURN *;

Also check if Orders.product is found in Products.product_id by running this query:

MATCH (o:Orders) 
MATCH (p:Products) WHERE p.product_id = o.product
RETURN n LIMIT 5

If you the query does not return any result, then your Orders and Products are not matching

Related