首页 > 解决方案 > 从一个节点到另一个节点的多个关系

问题描述

我是neo4j的新手。我有一个 .csv 文件,其中两列由“,”分隔。第一列包含名字,第二列包含姓氏:

Lname,Fname
Brown,Helen
Right,Eliza
Green,Helen
Pink,Kate
Yellow,Helen

我想为 Lname 列创建节点,为Fname创建节点。对于具有相同 Fname 的行,我想将 Lname 连接到相应的 Fname。例如,我想要一个“Helen”节点,其中三个节点“Brown”、“Green”和“Yellow”连接到“Helen”。我还想将“Fname”节点连接到“中心节点”。我写了这段代码:

LOAD CSV WITH HEADERS FROM 'file:///names.csv' AS row
WITH row.Fname AS first, row.Lname AS last
MERGE (p:la {last: last})
MERGE (o:fi {first: first})
MERGE (c:central {name: "central node"})
MERGE (c)-[r:CONTAINS {first:first}]->(o)-[rel:CONTAINS {first: first}]->(p)
RETURN count(o)

当我运行此代码并使用此查询显示输出时:

MATCH (c:central)-[r:CONTAINS]->(o:fi)-[rel:CONTAINS]->(p:la)
RETURN c, r, o, rel, p

我收到此图作为输出: 图形

如您所见,根据姓氏的数量,我与名字的关系数量相同,例如我有 3 个从“中心节点”到“海伦”的关系,但我只想要一个来自“中心节点”的关系到“海伦”。这里有什么问题?

标签: neo4j

解决方案


The answer lies in your final MERGE clause.

MERGE (c)-[r:CONTAINS {first:first}]->(o)-[rel:CONTAINS {first: first}]->(p)

Neo4j will take this entire pattern and ensure it is unique. Since each time it is invoked (due to the last name changing) the whole thing is created. If you would like to have a single relationship from the central to the first name nodes then you need to split it up into two separate parts. Using the following the first MERGE will only create the central-first relationship once.

MERGE (c)-[r:CONTAINS {first:first}]->(o)
MERGE (o)-[rel:CONTAINS {first: first}]->(p)

推荐阅读