George Fletcher
George Fletcher

Reputation: 21

variable length matching over paths in Cypher

Is it possible to allow variable length matching over multiple paths in Cypher? By a path I mean something like two KNOWS traversals or three BLOCKS traversals, where KNOWS and BLOCKS are relationship types in my graph. For example, I'd like to be able to write something like:

MATCH (s)-[r*]->(t) 
WHERE ALL (x in type(r) WHERE x=KNOWS/KNOWS OR x= BLOCKS/BLOCKS/BLOCKS)
RETURN s, t

where by "KNOWS/KNOWS" I mean something like (a)-[:KNOWS]->(b)-[:KNOWS]->(c). I want to do this without changing the data itself, by adding relationships such as KNOWS/KNOWS, but rather just as a cypher query.

Upvotes: 2

Views: 140

Answers (1)

FrobberOfBits
FrobberOfBits

Reputation: 18002

Yes, you can do this. It's actually much easier than you think:

MATCH p=(s)-[r:KNOWS|BLOCKS*]->(t) 
RETURN s, t;

When you specify the r, with a colon you can indicate which types you want to traverse, and separate them by a pipe for OR. The asterisk just operates the way you expect.

If you only want one type of relationship at a time you can do this:

OPTIONAL MATCH p1=(s1)-[r1:KNOWS*]->(t1)
OPTIONAL MATCH p2=(s2)-[r2:BLOCKS*]->(t2)
RETURN p1, p2;

If you want exactly two knows and 3 blocks, then it's:

OPTIONAL MATCH p1=(s1)-[:KNOWS]->()-[:KNOWS]->(t1)
OPTIONAL MATCH p2=(s2)-[:BLOCKS]->()-[:BLOCKS]->()-[:BLOCKS]->(t2)
RETURN p1, p2;

Upvotes: 2

Related Questions