Jonathan
Jonathan

Reputation: 1402

How to match a variable length pattern in neo4j?

I have the following simple neo4j graph structure:

(A)-[:A_TO_B]->(B)

Any (B) node can only ever have 2 (A) nodes pointing to it, meanwhile any (A) node can point to roughly 20 (B) nodes.

I would like to be able to find paths connecting (start:A) and (end:A) up to a specified depth and return all nodes and relationships in the path. For example:

1. (start:A)-[:A_TO_B]->(B)<-[:A_TO_B]-(end:A)
2. (start:A)-[:A_TO_B]->(B)<-[:A_TO_B]-(A)-[:A_TO_B]->(B)<-[:A_TO_B]-(end:A)
3. (start:A)-[:A_TO_B]->(B)<-[:A_TO_B]-(A)-[:A_TO_B]->(B)<-[:A_TO_B]-(A)-[:A_TO_B]->(B)<-[:A_TO_B]-(end:A)

Which basically boils down to these patterns: [A B A], [A BAB A], [A BABAB A] ...

The following are my unsucessful attempts:

MATCH path=(start:A)-[:A_TO_B*0..2]->(end:A)
RETURN path;

MATCH path=(start:A)-[:A_TO_B*0..2]->(B)<-[:A_TO_B*0..2]-(end:A)
RETURN path;

MATCH path=(start:A)-[:A_TO_B*0..2]->(A)<-[:A_TO_B*0..2]-(end:A)
RETURN path;

Upvotes: 0

Views: 385

Answers (1)

Frank Pavageau
Frank Pavageau

Reputation: 11705

Because you need to alternatively follow the relationship in one direction then the other, you have to drop the direction from the query:

MATCH path = (start:A)-[:A_TO_B*0..2]-(end:A)
RETURN path;

Unfortunately, you can't (yet) declare a repeatable pattern, only repeatable relationships.

Upvotes: 2

Related Questions