我有一个具有以下格式关系的文件:
!comment
!comment
nodeID nodeName edgeType nodeID
nodeID nodeName edgeType nodeID
nodeID nodeName edgeType nodeID
我想将该文件的节点和边缘导入到我的neo4j数据库中。
我尝试了以下步骤:
// Each node id is unique
CREATE CONSTRAINT ON (n:Node) ASSERT n.id IS UNIQUE
// For each row not starting by "!", create node if it doesn't exist
LOAD CSV FROM "file:///relationships.tsv" AS row
FIELDTERMINATOR '\t'
WITH row
WHERE NOT row =~ '^!.*'
CREATE (:Node {id: row[0], name: row[1]})
// For each row not starting by "!", create edge
LOAD CSV FROM "file:///relationships.tsv" AS row
FIELDTERMINATOR '\t'
WITH row
WHERE NOT row =~ '^!.*'
MATCH (n:Node), (m:Node)
WHERE n.id = row[0] AND m.id = row[3]
WITH n, m, row
CASE row[2]
WHEN 'F' THEN
CREATE UNIQUE (m)-[:Edge {type: 'friend'}]->(n)
WHEN 'P' THEN
CREATE UNIQUE (m)-[:Edge {type: 'partner'}]->(n)
END
上面的代码不起作用。对cypher陌生,我不确定自己做错了什么。我最终希望合并步骤2和3,以一次读取文件并完成处理。如何有效导入这些数据?
答案 0 :(得分:0)
[更新两次]
此版本的第三个查询应该可以工作:
LOAD CSV FROM "file:///relationships.tsv" AS row
FIELDTERMINATOR '\t'
WITH row
WHERE NOT row[0] STARTS WITH '!'
MATCH (m:Node)
WHERE m.id = row[3]
MERGE (n:Node {id: row[0]})
SET n.name = row[1]
FOREACH (domain IN
CASE
WHEN row[2] = 'F' THEN ['friend']
WHEN row[2] = 'P' THEN ['partner']
ELSE []
END |
MERGE (t)-[:Edge {type: domain}]->(p)
);
它将正确地测试行中的第一个项目(不是整个行 list ,它不是字符串)是否以'!'开头。它还使用FOREACH
子句执行条件更新(Cypher CASE
子句本身不支持)。此查询还使用MERGE
代替不推荐使用的CREATE UNIQUE
。并且它还使用MERGE
而非CREATE
来创建n
节点,以确保您不会产生重复项(例如,如果您重新运行相同的查询)。 / p>