问题
I'm new to neo4j. I have a .csv file with two columns separated by ",". The first column contains first names and the 2nd column contains the last names:
Lname,Fname
Brown,Helen
Right,Eliza
Green,Helen
Pink,Kate
Yellow,Helen
I want to create nodes for Lname column and nodes for Fname column. For the rows that have the same Fname, I want to connect Lname to the corresponding Fname. For example I want to have a "Helen" node that three nodes "Brown", "Green" and "Yellow" connected to "Helen". I also want to connect "Fname" nodes to a "central node". I have written this code:
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)
when I run this code and display the output using this query:
MATCH (c:central)-[r:CONTAINS]->(o:fi)-[rel:CONTAINS]->(p:la)
RETURN c, r, o, rel, p
I receive this graph as output:
As you see according to the number of last names, I have the same number of relationships to the first names, For example I have 3 relationships from "central node" to "Helen", but I want only one relationship from "central node" to "Helen". What's wrong here?
回答1:
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)
来源:https://stackoverflow.com/questions/60187636/several-relationships-from-a-node-to-another-node