2014-02-25 51 views
2

獲取僅NDB查詢結果計數的最佳方式是什麼? (用較少的讀取操作)獲取NDB查詢計數的最佳方式 - App Engine

哪一個更有效地獲得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,但它是爲獲得第一查詢結果。

回答

7

有一個count操作。

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

count(limit=None, **q_options)

返回查詢結果,高達 到了一個極限的數量。這將返回與len(q.fetch(limit))相同的結果,但會更加高效地返回 。

+4

小心,因爲在這種情況下'更高效'將只是一個常數。當appengine遍歷索引時,它仍然是時間並且與查詢長度成比例。對於非常大的結果也會超時,您需要對其進行分頁。 –

2

使用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} 
相關問題