I'm trying to write a query that will create some relationships if another relationship already exists.
START a=node(1), b=node(2), c=node(3)
OPTIONAL MATCH a-[r1:RELATIONSHIP]-(optional1)
OPTIONAL MATCH b-[r2:RELATIONSHIP]-(optional2)
CREATE c-[:NEW_RELATIONSHIP]->(optional1)
CREATE c-[:NEW_RELATIONSHIP]->(optional2)
DELETE r1, r2
RETURN a, b, c
The query returns an error:
"Expected optional1
to a node, but it is a null"
Is there a way to create the new relationship if the existing relationship exists? Otherwise just ignore the create?
For now, you can work around this using FOREACH
and CASE
. For example:
START a=node(1), b=node(2), c=node(3)
OPTIONAL MATCH (a)-[r1:RELATIONSHIP]-(optional1)
OPTIONAL MATCH (b)-[r2:RELATIONSHIP]-(optional2)
FOREACH (o IN CASE WHEN optional1 IS NOT NULL THEN [optional1] ELSE [] END |
CREATE (c)-[:NEW_RELATIONSHIP]->(optional1)
)
FOREACH (o IN CASE WHEN optional2 IS NOT NULL THEN [optional2] ELSE [] END |
CREATE (c)-[:NEW_RELATIONSHIP]->(optional2)
)
DELETE r1, r2
RETURN a, b, c
I suspect this will be made simpler in future Cypher language updates.
PS. You probably shouldn't use START
anymore, but I imagine you have simply for the convenience of an example.