cancel
Showing results forΒ
Did you mean:Β

Head's Up! Site migration is underway. Expect disruption to service on Thursday, Feb. 9!

## Match Variable length paths with different relationship types

Node Clone

Hi,
I am trying to write a Cypher query to return the start and end nodes of all the patterns(subgraphs/paths) that are in the following regular expression:

`A.(B|C.D)*.E`

Start node: A
End node: E
Relationship Types: B,C,D
The path will have different combinations of B or C and D (C followed by D).

I know we can use "*" for variable length paths (like B*1..5) and "|" for OR between the relationships (like, :C|:D for either C or D).

How can I match C and D both sequentially?
(I tried :C|:D and :C|D both gives a result for C OR D)

Is it possible to write Cypher query for patterns (Regular Expression) as I mentioned above?

Thanks

1 ACCEPTED SOLUTION
Neo4j

I'm not aware of any way to do this at this time.

APOC path expander procedures have support for sequences of relationships, so if you just needed alternating :C and π relationships it could support that, but we can't mix in :B as well.

One thing you could do is MATCH to the :C followed by π pattern and create a new relationship for this:

``````MATCH (start)-[:C]-()-[:D]-(end)
CREATE (start)-[:CD]->(end)
``````

That would allow you to use a path expander procedure from APOC and supply both the undirected :B relationship as well as the directed :CD relationship in the relationship filter:

``````MATCH (start:Node {name:'A'}), (end:Node {name:'E'})
CALL apoc.path.expandConfig(start, {terminatorNodes:[end], relationshipFilter:'B | CD>'}) YIELD path
RETURN path
``````
2 REPLIES 2
Neo4j

I'm not aware of any way to do this at this time.

APOC path expander procedures have support for sequences of relationships, so if you just needed alternating :C and π relationships it could support that, but we can't mix in :B as well.

One thing you could do is MATCH to the :C followed by π pattern and create a new relationship for this:

``````MATCH (start)-[:C]-()-[:D]-(end)
CREATE (start)-[:CD]->(end)
``````

That would allow you to use a path expander procedure from APOC and supply both the undirected :B relationship as well as the directed :CD relationship in the relationship filter:

``````MATCH (start:Node {name:'A'}), (end:Node {name:'E'})
CALL apoc.path.expandConfig(start, {terminatorNodes:[end], relationshipFilter:'B | CD>'}) YIELD path
RETURN path
``````
Node Clone

Thank you, Andrew.
It helped me!

Nodes 2022

NODES 2022, Neo4j Online Education Summit

All the sessions of the conference are now available online

Neo4j Resources