AggregationQueries - objectify/objectify GitHub Wiki
The datastore supports server-side aggregation queries. Objectify provides convenience methods, plus a general mechanism that lets you use the aggregation feature of the low-level API directly.
It is helpful to read the Google Cloud Datastore Aggregation Queries documentation. Pay particular attention to the behavior and limitations.
Count
The count method has long been a part of Objectify. As of v6.1, it is now implemented with a server-side aggregation query:
final long count = ofy().load().type(Thing.class).count();
Sum and Average
You can sum or average by fields in an entity:
final double avg = ofy().load().type(Thing.class).avg("aNumericField");
final double sum = ofy().load().type(Thing.class).sum("aNumericField"); // floating-point
final long sum2 = ofy().load().type(Thing.class).sumLong("aNumericField"); // integer
Generalized aggregation
Objectify provides a way of using the cloud SDK aggregation objects directly. This allows you to perform multiple aggregations at once, as well as future-proofing should Google add more aggregation methods in the future.
import com.google.cloud.datastore.AggregationResult;
import com.google.cloud.datastore.aggregation.Aggregation;
// Get the count, sum, and average in one query
final AggregationResult agg = ofy().load().type(Thing.class).aggregate(
Aggregation.count().as("count"),
Aggregation.sum("aNumericField").as("sum"),
Aggregation.avg("aNumericField").as("avg")
);
final long count = agg.getLong("count");
final double sum = agg.getDouble("sum");
final double sum = agg.getDouble("avg");