Neo4J: Compare a property value gathered with "order by Limit 1" with a property value of another label

Viewed 38

There are two labels Car and Session. The Sessions are ordered descending with limit 1 to get the latests Session. This latest Session has one playerVehicleIdx as property. This exact playerVehicleIdx should be matched with the right vehicleIdx of the Cars available.

Idea:

MATCH (m:Car) with (n:Session) Return n ORDER BY n.sessionStart DESC LIMIT 1 
WHERE n.playerVehicleIdx = m.vehicleIdx RETURN m,n

The query is wrong and i tried many different variants that did not work as well. How to fix the query to compare the property value of the one node that comes from the sorting of the Sessions with the property value of the Cars?

1 Answers

First, you should create a relationship between Car and Session using vehicleIdx. Then run below query:

// Get all car and session
MATCH (c:Car)--(s:Session)
// Group by car, get the latest session based on sessionStart
WITH c, collect(s)[0] as s ORDER BY s.sessionStart DESC 
// When there are more than 1 session per car, it will get the top session record  where [0] is the index of the first record
RETURN c, s
Related