user8164962
user8164962

Reputation:

I can't create a relationship between nodes and predecessors by cypher while creating the graph

I have the following file A.csv

"NODE","PREDECESSORS"
"1",""
"2","1"  
"3","1;2"

I want to create with the nodes: 1,2,3 and its relationships 1->2->3 and 1->3 I have already tried to do so:

LOAD CSV WITH HEADERS FROM  'file:///A.csv' AS line 
CREATE (:Task { NODE: line.NODE, PREDECESSORS: SPLIT(line.PREDECESSORS ';')})
FOREACH (value IN line.PREDECESSORS | 
          MERGE (PREDECESSORS:value)-[r:RELATIONSHIP]->(NODE) )

But it does not work, that is, it does not create any relationship. Please, might you help me?

Upvotes: 0

Views: 113

Answers (1)

InverseFalcon
InverseFalcon

Reputation: 30397

The problem is in your MERGE:

MERGE (PREDECESSORS:value)-[r:RELATIONSHIP]->(NODE)

This is merging a :value labeled node and assigning it to the variable PREDECESSORS, which can't be what you want to do.

A better approach would be not save the predecessor data in the node, just use that to match on the relevant nodes and create the relationships.

It will also help to have an index on :Task(NODE) so your matches to the predecessors are quick.

Remember also that cypher queries do not process the entire query for each row, but rather each operation in the query is processed for each row, so once the CREATE executes, all nodes will be created, there's no need to use MERGE the predecessor nodes.

Try something like this:

LOAD CSV WITH HEADERS FROM  'file:///A.csv' AS line 
CREATE (node:Task { NODE: line.NODE})
WITH node, SPLIT(line.PREDECESSORS, ';') as predecessors
MATCH (p:Task)
WHERE p.NODE in predecessors
MERGE (p)-[:RELATIONSHIP]->(node)

Upvotes: 1

Related Questions