2
votes

I'm trying to write a merge query for a relationship between two nodes. The tricky part is that if I don't find node with my second match I want to make another match to look for a "fallback" node with different filtering conditions for the merge request.

To make it short : I want to merge (A)->(B) if B exists and (A)->(C) if B does not exist.

This is what I came up with after looking at different posts :

MATCH (n:ArticleConv {id:"firstId"}) OPTIONAL MATCH (m:ArticleCode {name:"targetName"}) WHERE m.begin <= n.begin <= m.end OPTIONAL MATCH (l:ArticleCode {num:"targetName"}) WHERE not(()-[:Version]->(l)) FOREACH (o IN CASE WHEN m IS NOT NULL THEN [m] WHEN m IS NULL AND l IS NOT NULL THEN [l] ELSE [] END | MERGE (n)-[r:Link]->(o))

However it is not working as intended : if both optional match nodes are not null then two relationships are created targeting each nodes.

Thanks!

1

1 Answers

1
votes

You can do something like that :

MATCH (n:ArticleConv {id:"firstId"})
OPTIONAL MATCH (m:ArticleCode {name:"targetName"}) WHERE m.begin <= n.begin <= m.end
OPTIONAL MATCH (l:ArticleCode {num:"targetName"}) WHERE not(()-[:Version]->(l))
WITH n, coalesce(m,l) AS node WHERE node IS NOT NULL
  MERGE (n)-[r:Link]->(node)

Cheers