Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable to create relationship in cypher?

Tags:

neo4j

cypher

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?

like image 995
Petey B Avatar asked Oct 24 '16 18:10

Petey B


1 Answers

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
like image 188
cybersam Avatar answered Oct 12 '22 20:10

cybersam