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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With