Search code examples
cypherredisgraph

How to order an array property by any of its properties in Redisgraph?


I'm using Redisgraph. I have two node types, Driver and Race, with a relationship from Driver to Race called racedAt. I know that if I query:

MATCH (r:Race)<-[p:racedAt]-(d:Driver)
RETURN r,p

This returns me the same race n times, where n is the number of drivers. To solve this, I use:

MATCH (r:Race)<-[p:racedAt]-(d:Driver)
RETURN r, collect(p) as p

to have a single Race in _values[0] and every racedAt in _values[1].

Lets' suppose that the racedAt relationship has a property, position; what can I do to sort the _values[1] array by its inner property position?

The result I have:

_values[0]: { name: 'Monza' }
_values[1]: [ { driver: 'Hamilton', position: '2'}, { driver: 'Verstappen', position: '1'} ]

The result I want:

_values[0]: { name: 'Monza' }
_values[1]: [ { driver: 'Verstappen', position: '1'}, { driver: 'Hamilton', position: '2'} ]

Thank you!


Solution

  • Use ORDER BY before you collect the results:

    MATCH (r:Race)<-[p:racedAt]-(d:Driver)
    WITH r, p
    ORDER BY p.position
    RETURN r, collect(p) AS p