jKraut
jKraut

Reputation: 2487

neo4j Import set Relationships

I have the following dataset with headers I'm using neo4j to create a graph database:

 context_id,    item_type,  category
 u1,            product,    TVs
 u1,            THX,        TVs
 u2,            THX,        Receivers
 u2,            product,    PS4
 u2,            product,    Receivers

Code:

 LOAD CSV WITH HEADERS FROM 'file:///Users/neo4j.csv' AS line
 WITH line
 MERGE (cust:Cust { c_id: line.context_id})
 CREATE (cat:Cat {cat_nm: line.category})
 CREATE (cust)-[r:ACTION{type:line.item_type}]->(cat);

This processes, but it has two issues I want to solve:

1) the relationship is just called ACTION, and I'd like two relationships, "product" and "THX" 2) the other, is right now the category are not nodes, and I believe they should be.

I want nodes of both context_id and category. That way I can see relationship between using values of item_type with other categories.

It is also not required I need to perform these functions on the load. Thanks.

Upvotes: 0

Views: 69

Answers (2)

William Lyon
William Lyon

Reputation: 8546

I'm assuming that when the value of item_type is "product" you want the relationship type to be :PRODUCT and when item_type is "THXyou want the relationship type to be:THX`.

Since relationship types cannot be parameterized in Cypher you use something like this to accomplish this:

LOAD CSV WITH HEADERS FROM 'file:///Users/neo4j.csv' AS line
WITH line
MERGE (cust:Cust { c_id: line.context_id})
MERGE (cat:Cat {cat_nm: line.category})
FOREACH (r IN (CASE WHEN line.item_type = "product" THEN [1] ELSE [] END) |
    CREATE (cust)-[:Product]->(cat))
FOREACH (r in (CASE WHEN line.item_type = "THX" THEN [1] ELSE [] END) |
    CREATE (cust)-[:THX]->(cat))

Note that we are using a CASE clause to populate an array with one element when a condition is true, then iterating over the elements of that array (a single dummy item) using FOREACH to create the relationship if our CASE condition matches.

Upvotes: 1

Stefan Armbruster
Stefan Armbruster

Reputation: 39915

There is currently no direct way to deal with dynamic relationship types. The way to deal with it is either:

  1. create a separate csv file for each relationship type (THX, product)
  2. use the famous FOREACH ... CASE WHEN trick described at http://www.markhneedham.com/blog/2014/06/17/neo4j-load-csv-handling-conditionals/

For your 2nd question you have to provide more information how the categories should be connected, this information is not in the csv.

Upvotes: 1

Related Questions