Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CREATE after OPTIONAL MATCH where no match was found

Tags:

neo4j

cypher

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?

like image 598
rorymadden Avatar asked Apr 24 '14 16:04

rorymadden


People also ask

What is the difference between optional match and match?

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.

How do you create a relationship between two nodes in neo4j?

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.


1 Answers

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.

like image 165
Chris Leishman Avatar answered Sep 23 '22 11:09

Chris Leishman