Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to 'repeat' a pattern of more than one hop in Cypher?

Tags:

neo4j

cypher

Imagine that there are two kinds of relations in a graph: :A and :B. There are patterns like (n1)-[:A]->(n2)->[:B]->(n3)->[:A]->(n4)->[:B]->(n5)->.... Here I only show 2 repetitions of this ':A, then :B' pattern, but it could be repeated to arbitrary depth. It could be interesting to query for something like 'start with node X, then follow this A+B pattern as far as you can, then take the resulting node Y'.

In Gremlin, one can use repeat step to implement such a query.

In Cypher, there are variable length patterns https://neo4j.com/docs/cypher-manual/current/syntax/patterns/#cypher-pattern-varlength , so we could write something like (x)-[:A*]->(y) for a simple repetition pattern where we just repeat one hop.

But could we do the same for a more complex pattern (like the one I described, the A+B pattern)?

I found this Repetitive pattern of relationships in cypher where they recommend using a procedure, but it's not pure Cypher (and it's a non-standard extension by Neo4J not available in other systems implementing Cypher).

like image 961
Roman Puchkovskiy Avatar asked Oct 24 '25 14:10

Roman Puchkovskiy


1 Answers

Currently the APOC approach with relationship sequences is the only option.

MATCH (start:Node {id:123})
CALL apoc.path.expandConfig(start, {relationshipFilter:'A,B'}) YIELD path

We definitely want the ability to capture repeating sequences, both in this more simple example and in more complex use cases, and there are already design discussions around them. So this isn't here yet, but it's only a matter of time to design and implement a good solution.

like image 96
InverseFalcon Avatar answered Oct 26 '25 04:10

InverseFalcon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!