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?
An OPTIONAL MATCH matches patterns against your graph database, just like a MATCH does. The difference is that if no matches are found, OPTIONAL MATCH will use a null for missing parts of the pattern. OPTIONAL MATCH could be considered the Cypher equivalent of the outer join in SQL.
To create a relationship between two nodes, we first get the two nodes. Once the nodes are loaded, we simply create a relationship between them. The created relationship is returned by the query.
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.
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