nithin ks
nithin ks

Reputation: 285

cypher query - check for a relationship if not present check for another one

I would like to check if a relationship exist from a node, and in case its not found, then i want to check for another relationship type from the same node.

Something like, (a:Type)-[:relation1]-(b) if relation1 exist query returns node b. If not exist, then will check for another relationship like, (a:Type)-[:relation2]-(b) and returns node b.

I want to know how this can be writen as a single cypher query. Any help would be appreciated. Thanks.

Upvotes: 3

Views: 803

Answers (2)

InverseFalcon
InverseFalcon

Reputation: 30417

You may be able to use COALESCE() to make a backup choice in case the node at the first relation is null.

// after you've already matched to a
OPTIONAL MATCH (a)-[:relation1]-(b)
OPTIONAL MATCH (a)-[:relation2]-(c)
WITH a, COALESCE(b, c) as b // will use node c if b is null
...

Upvotes: 2

Tom Geudens
Tom Geudens

Reputation: 2666

What about using a UNION ?

MATCH (a:Type)-[:relation1]-(b)
RETURN b
UNION
MATCH (a:Type)-[:relation2]-(b)
RETURN b

Hope it helps, Tom

Upvotes: 2

Related Questions