wvb1
wvb1

Reputation: 63

Count entities in datastore Google app engine

In my GAE application I have a survey. For example one question is "where do you live?". If we are using the google guestbook example application the key would be guestbook, and in this I have created smaller keys like address, content2, content3. I have no problem posting or retrieving the individual results such as: "Fred MALE 24 Tokyo" "content1, gender, age, place". However on a separate page I want to show the total amount of people who took the survey; 10 people answered the survey - 3 Males 7 FEMALES. I also want to show results such as "10 people answered the survey in Tokyo." Can someone explain a way to count like this with the datastore? It would also help if your answer was in the context of Google`s guestbook example,or another simple example of GAE. お願いします!

Upvotes: 0

Views: 1519

Answers (2)

Zig Mandel
Zig Mandel

Reputation: 19835

There is count, see https://developers.google.com/appengine/docs/python/datastore/queryclass#Query_count However see the notes in there. In short:

  1. its time is proportional to the number of elements being counted

  2. If you have many elements it will timeout because of (1) so you would need to use limit an paginate client-side.

  3. its faster than iterating, but by a constant factor (because of #1)

For many elements your direction is to either use something like mapreduce, use cloud sql (easiest but $) or to maintain the counts yourself, usually with sharding and/or using memcached to improve performance and greatly reduce chances that simultaneous operations could lose data (because memcached supports atomic addition operations)

Upvotes: 2

farrellmr
farrellmr

Reputation: 1905

Do you mean a query like -

select count(*) from questionaires where sex = 'M'

I dont think you can return this from GAE datastore

The options are -

  • Return a list from a query and output its size

    @SuppressWarnings("unchecked")
    
    public List<Users> Users() {
    
        PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
    
        String query = "select from " + User.class.getName();
    
        return (List<User>) pm.newQuery(query).execute();
    
    }
    
  • Maintain a count on these fields in the datastore

Upvotes: 1

Related Questions