Richard Deurwaarder
Richard Deurwaarder

Reputation: 2040

How to match nodes in Cypher query based on different directions per relationship type

I've got a graph with two types of relationships: Sync and Async.

I want a query to give me a subgraph, meaning all the nodes that can be reached directly or indirectly.

This query works for this:

MATCH (s {type: 'service')
OPTIONAL MATCH (s)-[:Async|Sync*]->(dependent)
WITH s, COLLECT(DISTINCT dependent) AS allDependentNodes

This gives me every node that can be reached via an Sync or Async relationship.

But now I'd like to use a different direction based on the type of relation. I want nodes that can be reached via outgoing Sync a -> b OR reached via incoming Async a <- b.

So it's like an OR'd match condition. I've tried a few things without much success:

MATCH (s {type: 'service')
OPTIONAL MATCH (s)-[:Sync*]->(dependent), (s)<-[:Async*]-(d)
WITH s, totalNodes, COLLECT(DISTINCT dependent) AS allDependentNodes

How can I OR'd together relationship matches or how can I match different types of relationships with different directions?

Upvotes: 1

Views: 106

Answers (1)

Finbar Good
Finbar Good

Reputation: 1391

To follow all paths composed of relationships with either type Sync and direction outbound, or type Async and direction inbound, the following quantified path pattern will work:

MATCH (s {type: 'service'}) 
        ((n)-[r]-() WHERE (n = startNode(r) AND r:Sync) 
          OR (n = endNode(r) AND r:Async))+ (dependent)
RETURN s, collect(DISTINCT dependent) AS allDependentNodes

Upvotes: 1

Related Questions