ozzieisaacs
ozzieisaacs

Reputation: 843

Cyper Merge on Optional Match

I am trying to see if node :Customer exists based on a relationship in my optional match. I then want to create some relationships to my customer if they have an order. I am not sure what is the correct syntax for this.

MERGE (o:Order {account: 'j593jfsh', id: '35353'})
OPTIONAL MATCH (c:Customer)-[:HAS_ORDER]->(o)
MERGE (c)-[:HAS_SESSION]->(s)
MERGE (c)-[:HAS_ORDER]->(o)
WHERE c IS NOT NULL"

Upvotes: 3

Views: 295

Answers (1)

InverseFalcon
InverseFalcon

Reputation: 30397

One way you could do this is to use pattern comprehension in place of the OPTIONAL MATCH. This would collect all customers having orders into a list, and then you could use FOREACH to MERGE the relationships. If there are no customers, the list will be empty, and FOREACH will have nothing to process.

...
MERGE (o:Order {account: 'j593jfsh', id: '35353'})
WITH o, s, [(c:Customer)-[:HAS_ORDER]->(o) | c] as customers
FOREACH (c in customers | 
 MERGE (c)-[:HAS_SESSION]->(s)
 MERGE (c)-[:HAS_ORDER]->(o)
)
...

Upvotes: 4

Related Questions