3

I want to query all paths of arbitrary length

(a)-[:Relation*]->(b)

where for each pair (r1, r2) of consecutive relationships

()-[r1]->()-[r2]->()

a condition, say r2.foo > r1.foo, is met.

You can imagine foo being a timestamp and I only want to find paths where all steps are in chronological order.


What I currently have is this:

MATCH path = ()-[:Relationship*]->()
WITH rels(path) AS rels, path
WHERE reduce(acc = { inOrder: true, previous: rels[0] }, r IN tail(rels) |
    { inOrder: acc.inOrder AND r.foo > acc.previous.foo, previous: r }).inOrder
RETURN path

Now, this seems to work. However, I'm not sure if this is the most efficient query. Is there a better way to do it?

Kirill Rakhman
  • 42,195
  • 18
  • 124
  • 148

1 Answers1

5

You can actually do it, by playing with the ALL predicate on the size of the relationships collection of the path, example :

MATCH p=(a:Cool)-[*]->(c) 
WHERE ALL ( x IN range(1, length(p)-1) WHERE (rels(p)[x]).i > (rels(p)[x-1]).i ) 
AND length(p) > 1
RETURN p

The i property in my query would be your relationship's timestamp property

Working example here :

http://console.neo4j.org/r/2bzo4m

Christophe Willemsen
  • 19,399
  • 2
  • 29
  • 36