Laurent Grégoire
Laurent Grégoire

Reputation: 4146

Objectify/AppEngine: best way to count # of objects returned by a query?

What would be the best (i.e. most efficient) way of counting the number of objects returned by a query, w/o actually loading them, using Objectify on AppEngine? I'm guessing the best is to fetch all the keys and counting the result:

public int getEntityCount(Long v) {
    Objectify ofy = ObjectifyService.begin();
    Iterable<Key<MyEntity>> list = ofy.query(MyEntity.class)
            .filter("field", v).fetchKeys();
    int n = 0;
    for (Key<MyEntity> e : list)
        n++;
    return n;
}

Doesn't seems to have any dedicated method for doing that. Any ideas?

Upvotes: 8

Views: 4455

Answers (1)

Laurent Gr&#233;goire
Laurent Gr&#233;goire

Reputation: 4146

Found it:

int n = Iterable<Key<MyEntity>> list = ofy().query(MyEntity.class)
      .filter("field", v).count();

It's that simple, though efficient because it retrieves all the keys. It's better to design your UI to handle unknown numbers of results (such as Google which gives clues to the number of pages but not the actual number)

Upvotes: 15

Related Questions