Date time ordered results relationship creation

Hello again guys,

with this query i get a list of nodes ordered by date. I need to create a relationship named "SEQUENCE" between each result, so the 1st is connected to the 2nd, the 2nd to the 3rd and so on.
How can i do that just by using cypher ?

MATCH (pg1:Perception_Group)
RETURN pg1.date
ORDER BY pg1.date ASC

trying this one from Mark Needham's website (https://markhneedham.com/blog/2014/04/19/neo4j-cypher-creating-relationships-between-a-collection-of-nodes-invalid-input/), but not working (getting "Error occurred: Type mismatch: expected Path but was List (line 5, column 30 (offset: 106)) "FOREACH(i in RANGE(0, length(pgs)-2) |" ^)

MATCH (pg:Perception_Group)
WITH pg
ORDER BY pg.date
WITH COLLECT(pg) AS pgs
FOREACH(i in RANGE(0, length(pgs)-2) |
  FOREACH(pg1 in [pgs[i]] |
    FOREACH(pg2 in [pgs[i+1]] |
      CREATE UNIQUE (pg1)-[:SEQUENCE]->(pg2))))

Well. made these changes and it is working. Any suggestions ?

MATCH (pg:Perception_Group)
WITH pg
ORDER BY pg.date
WITH COLLECT(pg) AS pgs
FOREACH(i in RANGE(0, size(pgs)-2) |
  FOREACH(pg1 in [pgs[i]] |
    FOREACH(pg2 in [pgs[i+1]] |
      MERGE (pg1)-[:SEQUENCE]->(pg2))))

Hello there,

I recreated your test and it is working indeed. Not sure if you still expect suggestions (as you asked), or it was a typo...

Anyway, as Mark already explained, the (still) necessary hack here is with the two intermediate FOREACH clauses. What each of them does is simply access a list element and return it as a node. This is because MERGE (or CREATE) do not accept indexed list items in their patterns, just nodes.

Hope it helps,
Chris

1 Like

Hi Chris,

thank you for your comment and for taking the time to recreate my test. It made me understand better the trick involved.

I always need other people's comments or suggestions, because with them i am able to learn cypher faster by getting all the tips and insights you guys share :slight_smile:

Also i am always concerned with performance and everyone's comments may show me better ways to do queries.

Cheers
José Salvador