How does one get a count of rows in a Datastore model in Google App Engine?

25,192

Solution 1

You should use Datastore Statistics:

Query query = new Query("__Stat_Kind__");
query.addFilter("kind_name", FilterOperator.EQUAL, kind);       
Entity entityStat = datastore.prepare(query).asSingleEntity();
Long totalEntities = (Long) entityStat.getProperty("count");

Please note that the above does not work on the development Datastore but it works in production (when published).

I see that this is an old post, but I'm adding an answer in benefit of others searching for the same thing.

Solution 2

As of release 1.3.6, there is no longer a cap of 1,000 on count queries. Thus you can do the following to get a count beyond 1,000:

count = modelname.all(keys_only=True).count()

This will count all of your entities, which could be rather slow if you have a large number of entities. As a result, you should consider calling count() with some limit specified:

count = modelname.all(keys_only=True).count(some_upper_bound_suitable_for_you)

Solution 3

count = modelname.all(keys_only=True).count(some_upper_limit)

Just to add on to the earlier post by dar, this 'some_upper_limit' has to be specified. If not, the default count will still be a maximum of 1000.

Solution 4

This is a very old thread, but just in case it helps other people looking at it, there are 3 ways to accomplish this:

  1. Accessing the Datastore statistics
  2. Keeping a counter in the datastore
  3. Sharding counters

Each one of these methods is explained in this link.

Solution 5

In GAE a count will always make you page through the results when you have more than 1000 objects. The easiest way to deal with this problem is to add a counter property to your model or to a different counters table and update it every time you create a new object.

Share:
25,192
Admin
Author by

Admin

Updated on December 07, 2020

Comments

  • Admin
    Admin over 3 years

    I need to get a count of records for a particular model on App Engine. How does one do it?

    I bulk uploaded more than 4000 records but modelname.count() only shows me 1000.