Order By and Group By in Google Datastore Node Query JS

Viewed 722

I am trying to write a datastore query in NodeJS.

I want to order by timestamp but also only distinct unique ID's (no duplicates) and only retrieve the latest datastore item for each unique ID.


For example

USER_ID - TIMESTAMP
10      - 1000
10      - 500
5       - 10
5       - 1500
5       - 50

I want the query to result with

USER_ID - TIMESTAMP
10      - 1000
5       - 1500

What I've tried:

datastore.createQuery('example')
  .groupBy('USER_ID')
  .order('USER_ID')
  .order('TIMESTAMP')

But it returns the data ordered by USER_ID, not TIMESTAMP


Here's a pastebin to help answer the question: https://pastebin.com/MQCibmiw

2 Answers

You'll need to do the sort by timestamp yourself. As previously mentioned, order by USER_ID takes priority, and it's needed because you are running a distinct on query for the grouping.

As Jim Morrison said, I don't think this is possible.

I filed a Feature Request on your behalf. Check if my understanding was correct and feel free to add as many details as you think is needed.

Meanwhile I think the only option you have is to order the TIMESTAMP "manually".

Related