Neo4j cypher - 导入CSV并根据csv值添加节点之间的关系

时间:2014-12-31 10:47:29

标签: neo4j cypher

在cypher中是否可以使用导入功能基于csv的值在节点之间创建不同的关系。

例如: 对于给定的csv数据

product_id  user_id  action
1           1        VIEW
1           2        PURCHASE

我需要创建产品节点(product_id),用户节点(user_id)以及“用户”和产品节点之间的VIEW或PURCHASE关系,具体取决于csv中的“操作”字段。

以下是我尝试过的方法。我知道语法不正确但只是想知道我想要做什么。

USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "file://pathto/product-event.csv" AS csvLine 
FIELDTERMINATOR ','
MERGE ( prod:Product{pid: toInt(csvLine.product_id)} )
MERGE ( usr:User { cid: toInt(csvLine.userid)  })
WITH prod,usr , CASE  
    WHEN csvLine.action ='VIEW' THEN  'VIEW'
    WHEN csvLine.action ='PURCHASE' THEN  'PURCHASE'
    ELSE 'VIEW' END AS action
MERGE (usr)-[:action]->(prod)



USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "file:///pathto/product-event.csv" AS csvLine 
FIELDTERMINATOR ','
MERGE ( prod:Product {pid: toInt(csvLine.productid) } )
MERGE ( usr:User { cid: toInt(csvLine.userid) }
    )
ON CREATE SET 
    prod.created=timestamp()
WHERE csvLine.action = 'VIEW'
MERGE (cust)-[:VIEW]->(prod)
WHERE csvLine.action = 'PURCHASE'
MERGE (usr)-[:PURCHASE]->(prod)

可能有简单的方法。但我没有在网上得到任何参考。感谢。

2 个答案:

答案 0 :(得分:7)

您不能拥有动态关系类型。但是,通过有条件地填充具有1或0个元素并应用FOREACH的数组,有一种解决方法:

USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "file://pathto/product-event.csv" AS csvLine 
FIELDTERMINATOR ','
MERGE ( prod:Product{pid: toInt(csvLine.product_id)} )
MERGE ( usr:User { cid: toInt(csvLine.userid)  })
FOREACH(ignoreMe IN CASE WHEN csvLine.action='VIEW' THEN [1] ELSE [] END | 
    MERGE (usr)-[:VIEW]->(prod) )
FOREACH(ignoreMe IN CASE WHEN csvLine.action='PURCHASE' THEN [1] ELSE [] END | 
    MERGE (usr)-[:PURCHASE]->(prod) )

另见http://www.markhneedham.com/blog/2014/08/22/neo4j-load-csv-handling-empty-columns

答案 1 :(得分:1)

不完全是你想要的,但可能有效:

USING PERIODIC COMMIT 
LOAD CSV WITH HEADERS FROM "file://pathto/product-event.csv" AS csvLine      
FIELDTERMINATOR ',' 
MERGE ( prod:Product{pid: toInt(csvLine.product_id)} )   
MERGE ( usr:User { cid: toInt(csvLine.userid)  }) 
MERGE (usr)-[:action {type: csvLine.action}]->(prod) )