fdv1980
fdv1980

Reputation: 11

traversing neo4j graph with conditional edge types

i have a fixed database that has the nodes connecting people and edges with six different types of relationships. to make it simple, I call in this post the types of relationships A, B, C, D, E and F. None of the relationships are directional. new at the syntax so thank you for help.

I need to get sets of relationships that traverses the graph based on a conditional path A to (B or C.D) to E to F. So this means that I first need the relationship that links two nodes ()-[:A]-(), but then I am confused about how to express a conditional relationship. To get to the next node, I need either B or C then D so that it is ()-[:B]-() OR ()-[:C]-()-[:D]-(). How to express this conditional traversal in the MATCH syntax?

Tried all of these and got syntax errors:

(node2:Node)-[rel2:B|rel3:C]-(node3:Node)
(node2:Node)-[rel2:B]OR[rel3:C]-(node3:Node)

Upvotes: 1

Views: 377

Answers (2)

cybersam
cybersam

Reputation: 67044

This pure-Cypher query should return all matching paths:

MATCH p=()-[:A]-()-[r:B|C|D*1..2]-()-[:E]-()-[:F]-()
WHERE (SIZE(r) = 1 AND TYPE(r[0]) = 'B') OR
      (SIZE(r) = 2 AND TYPE(r[0]) = 'C' AND TYPE(r[1]) = 'D')
RETURN p

The [r:B|C|D*1..2] pattern matches 1 or 2 relationships that have the types B, C, and/or D (which can include subpaths that you don't want); and the WHERE clause filters out subpaths that you don't want.

Upvotes: 2

InverseFalcon
InverseFalcon

Reputation: 30407

This isn't something that can really be expressed with Cypher, when the number of hops to traverse isn't the same.

The easiest way to do this would probably be to use apoc.cypher.run() from APOC Procedures to execute a UNION query to cover both paths, then work with the result of the call:

//assume `node2` is in scope
CALL apoc.cypher.run("MATCH (node2)-[:B]-(node3:Node) RETURN node3
 UNION
 MATCH (node2)-[:C]-()-[:D]-(node3:Node) RETURN node3",
 {node2:node2}) YIELD value
WITH value.node3 as node3 // , <whatever else you want in scope>
...

Upvotes: 0

Related Questions