Awesome
Awesome

Reputation: 6639

How to fetch nested child entities using parent entity key 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 query will be as follows:

DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

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

My required result should be Employee entities of John & Robert along with the respective Address entities.

Upvotes: 2

Views: 861

Answers (1)

Prakash Chandra
Prakash Chandra

Reputation: 48

Appengine documentation says:

public Query setAncestor(Key ancestor)

"Sets an ancestor for this query. This restricts the query to only return result entities that are descended from a given entity. In other words, all of the results will have the ancestor as their parent, or parent's parent, or etc. If null is specified, unsets any previously-set ancestor. Passing null as a parameter does not query for entities without ancestors (this type of query is not currently supported)."

So your code should work fine. It will return all the entities with Aaa as the ancestor i.e; both Employee (parent) and Address (parent's parent) entities.

Documentation Link

Upvotes: 3

Related Questions