Question:
I'm working with Google's Datastore and I'm not able to assemble a Query to return what I need.
Situation
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} ]
Problem
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?
Answer:
I decided as follows:
- A query that returns only the item codes filtering by
codCliente
, using the google cloudProjection
andDistinctOn
- A second query that returns only one record, using
FetchOptions.Builder.withLimit(1)
, filtered bycodItem
andcodCliente
sorted by rating
Query to fetch only the codItem:
public QueryResults<ProjectionEntity> getItem(int codCliente) {
Query<ProjectionEntity> query2 = Query
.newProjectionEntityQueryBuilder()
.setKind("Item")
.setProjection("CodItem")
.setDistinctOn("CodItem")
.setFilter(PropertyFilter.eq("codCliente", codCliente))
.build();
QueryResults<ProjectionEntity> tasks = getDatastore().run(query2);
return tasks;
}