获得NDB查询计数的最佳方式 - App Engine

时间:2014-02-25 13:44:34

标签: python google-app-engine app-engine-ndb

获取NDB查询结果的最佳方法是什么? (少读取操作)

哪一个更有效地获得NDB查询结果计数?普通查询或投影查询?:

EmailSent.query(EmailSent.unsub==True, EmailSent.mail_ref==mail_ref, projection=['to_email']).count()

EmailSent.query(EmailSent.unsub==True, EmailSent.mail_ref==mail_ref).count()

我在这里发现了同样的问题:Get NDB query length - using Python on Google App Engine,但它是用于获取第一个查询结果。

2 个答案:

答案 0 :(得分:9)

count次操作。

https://developers.google.com/appengine/docs/python/ndb/queryclass#Query_count

count(limit=None, **q_options)

  

返回查询结果的数量   达到极限。这返回与len(q.fetch(limit))相同的结果但是   更有效率。

答案 1 :(得分:1)

使用count。如果你能够分页,效率可以忽略不计。

list_of_emails = EmailSent.query(EmailSent.unsub==True)
total_count = list_of_emails.count()

offset = int(args['offset'])
limit = int(args['limit'])

list_of_emails, next_cursor, more = list_of_emails.fetch_page(limit, offset=offset)

prev_offset = max(offset - limit, 0)
prev = True if offset else False
next_ = True if more else False
next_offset = ''
if next_:
    next_offset = offset + limit

objects = map(lambda emails: func(emails), list_of_emails)
        return {'objects': objects, 'total_count': total_count, 'prev': prev, 'next': next_, 'prev_offset': prev_offset,
                'next_offset': next_offset}