Awesome
Awesome

Reputation: 6609

How to sort child entities using datastore api

Here I'm using Datastore API to create, update & retrieve entities.

My use case is, have to get the child and grand child entities of a parent entity.

My entity structure is as follows:

 Company
     --> Employee
            --> Address (Multiple Address entities).

Here I have Company entity key and I need to fetch Employee details along with all the Address entities configured to the employee.

Example:

Company --> Aaa
     Employee --> John 
                  Address --> California
                  Address --> Redwood
     Employee --> Robert
                  Address --> New York
                  Address --> Washington

My required result is:

  1. Employee entities of John & Robert along with the respective Address entities.

  2. Employee entities should be sort by name.

My query is as follows:

DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

Query query = new Query().setAncestor(companyKey);
datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());

Above query returning results specified in #1.

But not able to sort Employee entities by name using this query. When I tried to add sort clause query.addSort("name", SortDirection.ASCENDING) it is throwing an error as follows:

 java.lang.IllegalArgumentException: kind is required for all orders except __key__ ascending
at com.google.appengine.api.datastore.DatastoreApiHelper.translateError(DatastoreApiHelper.java:50)
at com.google.appengine.api.datastore.DatastoreApiHelper$1.convertException(DatastoreApiHelper.java:121)

How to sort child entities while using ancestor path in query ?

Upvotes: 1

Views: 554

Answers (1)

Sai Pullabhotla
Sai Pullabhotla

Reputation: 2207

Your query is considered to be a Kindless query, because you are not querying for a specific Kind (e.g. Address or Employee). You are just saying get me all Entities that have the specified ancestor. Kindless queries can only be sorted by Key (__key__). No other properties are supported.

The documentation states that -

Kindless queries

A query with no kind and no ancestor retrieves all of the entities of an application from Cloud Datastore. Such kindless queries cannot include filters or sort orders on property values. They can, however, filter on entity keys and use ancestor filters. Key filters can be used by specifying key as the property name:

You might want to look into modifying your model to store Addresses as an Embedded List into the Empoyee Entities and see if that works better.

Upvotes: 1

Related Questions