What's the best way to count results in GQL?

后端 未结 9 1531
情深已故
情深已故 2020-12-02 14:21

I figure one way to do a count is like this:

foo = db.GqlQuery(\"SELECT * FROM bar WHERE baz = \'baz\')
my_count = foo.count()

What I don\'

相关标签:
9条回答
  • 2020-12-02 15:17

    We now have Datastore Statistics that can be used to query entity counts and other data. These values do not always reflect the most recent changes as they are updated once every 24-48 hours. Check out the documentation (see link below) for more details:

    Datastore Statistics

    0 讨论(0)
  • 2020-12-02 15:18

    orip's solution works with a little tweaking:

    LIMIT=1000
    def count(query):
        result = offset = 0
        gql_query = db.GqlQuery(query)
        while True:
            count = len(gql_query.fetch(LIMIT, offset))
            result += count
            offset += LIMIT
            if count < LIMIT:
                return result
    
    0 讨论(0)
  • 2020-12-02 15:27

    Count functions in all databases are slow (eg, O(n)) - the GAE datastore just makes that more obvious. As Jehiah suggests, you need to store the computed count in an entity and refer to that if you want scalability.

    This isn't unique to App Engine - other databases just hide it better, up until the point where you're trying to count tens of thousands of records with each request, and your page render time starts to increase exponentially...

    0 讨论(0)
提交回复
热议问题