Expand a path until a node with certain degree

52 Views Asked by At

Is there a way to expand a path until I find a node with degree n? I have a starting point and want to follow the path until I find a node that has a degree of more than 2 (so it forks the path). Degree in this case is IN + OUT. I also need to be able to filter relationship types. So I need to find a path until I hit a node with degree > 2 but only a list of relationships is allowed.

1

There are 1 best solutions below

2
Christoffer Bergman On

One way is to use QPP's (Quantified Path Patterns) that were introduced in Neo4j 5.9.

This query will find a start node (one that has a property start set to true) and then expands until it finds a node that forks

MATCH p=(start {start: true})(()-->(n WHERE COUNT{(n)--()} < 3))*()-->(end WHERE COUNT{(end)--()} > 2)
RETURN p

You can read more on QPP's here:

https://neo4j.com/docs/cypher-manual/current/patterns/concepts/#quantified-path-patterns

You also wrote that you want to filter by relationship type. That can simply be done by adding that to the QPP. Let's say we only want to look at relationships of type :PATH:

MATCH p=(start {start: true})(()-[:PATH]->(n WHERE COUNT{(n)-[:PATH]-()} < 3))*()-[:PATH]->(end WHERE COUNT{(end)--()} > 2)
RETURN p

[EDIT]

Thinking more about it I realised that you could solve it with the traditional variable length relationships as well, so you don't necessarily have to resort to QPP's:

MATCH p=(start {start: true})-[:PATH*]->(end_but_one)-[:PATH]->(end)
WHERE COUNT{(end_but_one)--()} < 3 AND COUNT{(end)--()} > 2
RETURN p