database – Build Query for last record NoSQL Google Datastore


I'm working with Google's Datastore and I'm not able to assemble a Query to return what I need.


I have an Entity , with key pair {"item": codItem, "item": id} , still inside this Entity I have the codCliente property.

For example, we could have a JSON being saved like this ( id is the field of the record that google generates):

 [ {"id":2137847312334,"codItem":12,"codCliente":1,"dataRegistro":2017-04-23T18:25:43.511Z}, {"id":2183462352427,"codItem":15,"codCliente":1,"dataRegistro":2017-04-23T18:25:43.511Z}, {"id":9128734678236,"codItem":10,"codCliente":1,"dataRegistro":2017-04-23T18:25:43.511Z}, {"id":2137847312334,"codItem":12,"codCliente":1,"dataRegistro":2017-03-20T18:25:43.511Z}, {"id":2183462352427,"codItem":15,"codCliente":1,"dataRegistro":2017-03-20T18:25:43.511Z}, {"id":9128734678236,"codItem":10,"codCliente":1,"dataRegistro":2017-03-20T18:25:43.511Z} ]


When I set up the query to search for these results, filtering by client, with codCliente I still don't have the information about which codItem it has.

What I need is a way to just get one (only one) result of each codItem the codCliente referenced with dataRegistro younger. So with the example above I should have the first three JSON records back.

I am open to changes to the json document structure and keys. The only thing that can't be changed is having the information about which codItem the client has before making the query. Any idea?


I decided as follows:

  • A query that returns only the item codes filtering by codCliente , using the google cloud Projection and DistinctOn
  • A second query that returns only one record, using FetchOptions.Builder.withLimit(1) , filtered by codItem and codCliente sorted by rating

Query to fetch only the codItem:

public QueryResults<ProjectionEntity> getItem(int codCliente) {

   Query<ProjectionEntity> query2 = Query
    .setFilter(PropertyFilter.eq("codCliente", codCliente))

  QueryResults<ProjectionEntity> tasks = getDatastore().run(query2);
  return tasks;

Scroll to Top