简体   繁体   中英

Create multiple relationship between multiple nodes in neo4j

I have a CSV file with headers like

Relationshiptype         source                     target
Causative_of             Absorb_heat                Apply_heat
Inheritance              Absorb_heat                Transition
ReFraming_Mapping        Transition                 Transitionstate

I have to create relationship between this source & target and the relationship between this source & target will be "relationshiptype".

I have tried :

LOAD CSV WITH HEADERS FROM "file:///output.csv" AS line
CREATE (sub:Source {name:line.source})
CREATE (sup:Target {name:line.target})
CREATE (sub)-[:Causative_of]->(sup)
CREATE (sub)-[: Inheritance]->(sup)
CREATE (sub)-[: ReFraming_Mapping]->(sup)

RETURN sub,sup;

But this does not work. It randomly creates relationship between source & target.

I cant find any way to create this multiple relationships. Is there any way to do this? Please help.

There are several problems:

1) Because the nodes can be repeated, you should use MERGE instead of CREATE to add new nodes:

MERGE (sub:Source {name:line.source})

2) Since a node can be both a source and a target, it is not appropriate to use different labels. Use one, for example Item :

MERGE (sub:Item {name:line.source})

3) In the query you create three types of relationships at once, although you need to use the relationship type from the input data. The problem is that at the moment you can not set the type of relation from the variable in neo4 cyper . And also there is no conditional branch. Therefore, you can use the following trick with FOREACH [ http://markhneedham.com/blog/2014/06/17/neo4j-load-csv-handling-conditionals/ ]:

LOAD CSV WITH HEADERS FROM "file:///output.csv" AS line
MERGE (sub:Item {name:line.source})
MERGE (sup:Item {name:line.target})
FOREACH(ift in CASE WHEN line.Relationshiptype="Causative_of" THEN [1] ELSE [] END |
  CREATE (sub)-[:Causative_of]->(sup)
)
FOREACH(ift in CASE WHEN line.Relationshiptype="Inheritance" THEN [1] ELSE [] END |
  CREATE (sub)-[:Inheritance]->(sup)
)
FOREACH(ift in CASE WHEN line.Relationshiptype="ReFraming_Mapping" THEN [1] ELSE [] END |
  CREATE (sub)-[:ReFraming_Mapping]->(sup)
)
RETURN sub, sup

4) This is not very nice and efficient, so you can use the create.relationship function from the APOC library [ https://stackoverflow.com/a/40225888/4989460 ]:

LOAD CSV WITH HEADERS FROM "file:///output.csv" AS line
MERGE (sub:Item {name:line.source})
MERGE (sup:Item {name:line.target})
WITH sub, sup, line
CALL apoc.create.relationship(sub, line.Relationshiptype, NULL, sup) YIELD rel
RETURN sub, rel, sup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM