Finding paths with specific relationship properties and grouping results

Hi, I'm trying to build a cypher query that given a start node (in the example below, it's all nodes with property class=persons), finds each path where all relationships in the path have a date property that matches the input 'period' parameter. Effectively, the end node should be the one that does not have any forward relationships with the given date.

Secondly, I'm trying to group the resulting paths by the first downstream node AFTER the starting node. In my use case, the next downstream node after a 'persons' node would be a 'person' node. I want to collect all paths downstream of a given 'person' node and group them into one record.

Below example is as far as I've managed to get but it returns every step in the path as a new path so I have to then deduplicate afterwards which I want to avoid. I can't figure out how to write the query to end on a node with no subsequent relationships with a given property. Also, I have no idea how to group on the first downstream node.

Any help or ideas would be gratefully received!


WITH 'persons' as c, datetime('2021-01-01T23:59:59Z') as period 
OPTIONAL MATCH activity = (n {class:c})-[*]->(e) 
WHERE all(r in relationships(activity) WHERE 0 <= duration.inSeconds(r.dtob, period).seconds <= 86400) 
AND date(n.dtob) < date(period) AND NOT (e)-->() 
WITH n, e, activity, period 
RETURN id(n) as start, id(e) as end, activity, nodes(activity) as nodes, 
relationships(activity) as relationships