Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 622
Laurent Grégoire Avatar asked Feb 18 '11 15:02

Laurent Grégoire


1 Answers

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)

like image 138
Laurent Grégoire Avatar answered Sep 22 '22 13:09

Laurent Grégoire