Using variable to create relationship in cypher?

≯℡__Kan透↙ 提交于 2019-12-10 17:15:56

问题


I'm trying to create a relationship between nodes dynamically. The problem I am having is that I am unable to use a variable to specify the relationship type.

For example, I have the data:

{
    nodes: [
        {
             "name":"Node1"
        },
        ...
    ],
    relationships: [
        {
             "sourceNode": "Node1",
             "destinationNode": "Node2",
             "relationshipType": "FRIEND"
        },
        ...
    ]
}

Assume all nodes have been created.

I now want to create relationships between nodes of type relationshipType.

I'm trying to do this like so:

WITH {json} AS document
UNWIND document.relationships AS relationship
MATCH (pdt:Node {name: relationship.sourceNode})
MATCH (cdt:Node {name: relationship.destinationNode})
CREATE (pdt)-[r:relationship.relationshipType]->(cdt)
RETURN pdt.name,type(r),cdt.name

However it craps out at [r:relationship.relationshipType] because it is expecting an explicit type like [r:CHILD].

Is it possible to use a variable to set a relationship type?


回答1:


After installing the APOC plugin, you can use the apoc.create.relationship procedure to create relationships with dynamic types.

For example:

WITH {json} AS document
UNWIND document.relationships AS relationship
MATCH (pdt:Node {name: relationship.sourceNode})
MATCH (cdt:Node {name: relationship.destinationNode})
CALL apoc.create.relationship(pdt, relationship.relationshipType, NULL, cdt) YIELD rel
RETURN pdt.name, type(rel), cdt.name


来源:https://stackoverflow.com/questions/40225203/using-variable-to-create-relationship-in-cypher

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!