Nijin Narayanan
Nijin Narayanan

Reputation: 2279

Best way to get the count of NDB query - App Engine

What is the best way to get only the count of NDB query result? (with less read operation)

Which one is more efficient to get NDB query result count ? Normal Query or Projection Query ?:

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()

I found same kind of question here: Get NDB query length - using Python on Google App Engine, but it's for getting the first query result.

Upvotes: 3

Views: 7540

Answers (2)

Rad Apdal
Rad Apdal

Reputation: 462

Use count. Negligible differences in efficiency if you are able to paginate.

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}

Upvotes: 1

Paul Collingwood
Paul Collingwood

Reputation: 9116

There is a count operation.

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

count(limit=None, **q_options)

Returns the number of query results, up to a limit. This returns the same result as len(q.fetch(limit)) but more efficiently.

Upvotes: 10

Related Questions