Showing results for 
Search instead for 
Did you mean: 

MERGE to create new Relation from csv

Node Clone


I have two CSV files.

1. all_entities.csv: The list of all node entities and their attributes, e.g., name, type

2. relations.csv: Three columns that have EntityA, relation, EntityB


I created nodes using



LOAD CSV WITH HEADERS from "file:///all_entity.csv" AS row
MERGE (e:Entity {id: row.EntityId})
ON CREATE SET = row.EntityName,
              e.num = row.EntityNum,
              e.category = row.EntityType



I am trying to create relations using the below snippet, but it's not working:



LOAD CSV WITH HEADERS FROM "file:///relation.csv" as line
WITH line.sourceName AS sourceName, line.SourceId AS SourceId, line.sourceType AS sourceType,
        line.targetName AS targetName, line.targetId AS targetId, line.targetype AS targetype,
        line.RId AS RId, line.RName AS RName, line.RNum AS RNum
MATCH (a:Entity {id:SourceId, name: sourceName, category: sourceType}),
          (b:Entity {id:targetId, name: targetName, category: targetype})
MERGE (a)-[r:REL {id: RId, predicate: RName, Orignum:RNum}]-(b)



 Please, am I doing something wrong?



The syntax looks good. You are matching on several fields when finding the nodes for the relationships.  Is it possible those fields are not all set, so the match does not return what you expected. I make note of this because in your first script you are only setting these properties if the node is created. Is it possible that some of these nodes already exist and don’t have their name or category properties set?  If true, remove the ‘on create’ so every nodes’s properties are set during the first script. The second script may work then. Also, can you match solely on the ‘id’ property in your second script instead of matching on three parameters,  I assume the ‘id’ is unique, so that should be fine. If that resolves the issue alone, then your issue must be caused by nodes missing either or both of their name and category properties. 

Do you get what you expected from the data if you execute just the first two lines of the second query after replacing the ‘with’ with ‘return’, so you can see what is passed to the query. 

Graph Maven

Try this: Add WITH a, b between MATCH and MERGE  statements

MATCH (a:Entity {id:SourceId, name: sourceName, category: sourceType}),
(b:Entity {id:targetId, name: targetName, category: targetype})
WITH a, b
MERGE (a)-[r:REL {id: RId, predicate: RName, Orignum:RNum}]-(b)