Katedral Pillon Katedral Pillon - 1 month ago 6
Java Question

How to fetch the latest 25 entries from an App-Engine datastore entity kind

I have an entity kind (i.e. ~table) with thousands of entries. I want to fetch the latest 25 entries. How do I do that? The following logic is not working: it returns the oldest 25.

Filter timestampFilter = new FilterPredicate("lastestEditDate", FilterOperator.GREATER_THAN_OR_EQUAL, 0);
Query query = new Query(CatMeow.class.getSimpleName()).setFilter(timestampFilter);

FetchOptions options = FetchOptions.Builder.withLimit(25);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
QueryResultList<Entity> entities = datastore.prepare(query).asQueryResultList(options);


I believed I needed to change my logic entirely. Having thought about it, I didn’t think a timestamp filter was relevant. So I changed to the following logic, which also is not working: it’s not returning the latest entities.

Query query = new Query(CatMeow.class.getSimpleName()).
addSort("lastestEditDate", SortDirection.ASCENDING);
FetchOptions options = FetchOptions.Builder.withLimit(25);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
QueryResultList<Entity> entities = datastore.prepare(query).asQueryResultList(options);


So again, of thousands of entities, I need to grab the latest 25 that were added. How do I do that?

Answer

The SortDirection.ASCENDING means to get the oldest entities (i.e the ones with the smallest values of lastestEditDate) first.

What you want is exactly the opposite -- newest entities (i.e the ones with the largest values of lastestEditDate) first.

Therefore, use, instead, SortDirection.DESCENDING.