8

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?

Laurent Grégoire
  • 4,006
  • 29
  • 52

1 Answers1

15

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)

mjaggard
  • 2,389
  • 1
  • 23
  • 45
Laurent Grégoire
  • 4,006
  • 29
  • 52
  • 2
    Bear in mind that counting entities is always inefficient - O(n) time. If you expect there to be a lot, you should keep a persistent count instead. – Nick Johnson Feb 21 '11 at 02:35
  • Somehow inefficient, but at least it does not fetch entities, just keys, right? In my case there can be lots of "MyEntity" objects, but filter count is never that big (<100). – Laurent Grégoire Feb 21 '11 at 09:48
  • 1
    Doesn't this approach have a problem with the number of items fetched at once? I have tried similar approach but it ultimately did not work as the maximum count was 1000 (dev server). – petr May 01 '12 at 15:36
  • You should always access ofy via its static method ofy() and not keep a reference to it. – Moritz Jan 20 '13 at 16:07
  • True with v4, but the question was asked when v3 was still the latest version, and that code was following the v3 documentation coding style. Now in v4, it's bad practice, but not buggy... – Laurent Grégoire Jan 22 '13 at 07:45
  • Is there any way to do the count in an async manner ? (Without blocking) – Sathya Aug 15 '14 at 09:05