Executing dynamic Cypher
Cypher does not allow dynamic query execution. If you are getting a value in the data that you want to use as a label on the node, or you need to create a relationship with that name, that is not easy to do in Cypher. It is possible to use the FOREACH
trick to check for the value and make the code deterministic, but this is not a practicable solution if the number of combinations is more than five, for example. In these scenarios, APOC procedures can help us to either to build a string and execute it or add or create nodes and relationships with dynamic values:
- First, we will take a look at how to add a new label to a node using a dynamic value:
WITH {label: "MyTest", id:10 , name: 'Another'} as data
MERGE(p:Person {id:data.id})
SET p.name=data.name
WITH data, p
CALL apoc.create.addLabels([p], [data.label])
YIELD node
RETURN node
- This query creates a
Person
node with the data and appends the label from the input data using theapoc...