Python 2.7 has reached end of supportand will bedeprecatedon January 31, 2026. After deprecation, you won't be able to deploy Python 2.7applications, even if your organization previously used an organization policy tore-enable deployments of legacy runtimes. Your existing Python2.7 applications will continue to run and receive traffic after theirdeprecation date. We recommend thatyoumigrate to the latest supported version of Python.

NDB Query Class

This page describes how to use the legacy bundled services and APIs. This API can only run in first-generation runtimes in the App Engine standard environment. If you are updating to the App Engine Python 3 runtime, refer to themigration guide to learn about your migration options for legacy bundled services.

AQuery object represents an NDB query, a request for a filtered, sorted list of entities.

This page contains reference documentation. For a general discussion of NDB queries, seeQueries.

Query Options

Many query methods take a standard set of additionaloptions, either in the form of keyword arguments such askeys_only=True, or asQueryOptions object passed withoptions=QueryOptions(...).

Queries support a variety of configuration options. These are specified by keyword arguments to theQuery methods:

ArgumentTypeDefaultDescription
keys_onlyboolFalseAll operations return keys instead of entities.
projectiontuple (or list) of properties (or strings)NoneOperations return entities with only the specified properties set.projection=[Article.title, Article.date] orprojection=['title', 'date'] fetches entities with just those two fields set. (SeeProjection Queries.)
offsetint0Number of query results to skip.
limitintNo limitMaximum number of query results to return.
batch_sizeint20Batch size.

Affects efficiency of queries only; larger batch sizes use more memory but make fewer RPC calls.
prefetch_sizeintNoneOverrides batch size for first batch returned.
produce_cursorsboolFalseGenerate cursors from query (seeQuery Iterators.Query Cursors).
start_cursorCursorNoneStarting point for search(seeQuery Cursors).
end_cursorCursorNoneEnding point for search(seeQuery Cursors).
deadlineintDepends onContextOverrides RPC deadline (which defaults to 5 seconds if not overridden whenContext created)
read_policyndb.EVENTUAL_CONSISTENCYThe read policy. Set tondb.EVENTUAL_CONSISTENCY to get perhaps-quicker results without waiting for the Datastore to apply pending changes to all returned records.

To run a query with a specific set of options,pass the keyword arguments to the applicable method:

qry=Employee.query().filter(...).order(...)# Create a queryforacctinqry.fetch(10,offset=20):# Skip the first 20printacct

Occasionally, you might want to keep a set of query options around and use them in various places. While you could just keep them in a dictionary and pass this dictionary to the methods using**kwds, you can also create aQueryOptions object and pass it using the options keyword argument. The following two examples are equivalent:

qo=ndb.QueryOptions(keys_only=True,offset=20)results=qry.fetch(10,options=qo)results=qry.fetch(10,keys_only=True,offset=20)

Constructor

Typically, an application creates aQuery by callingModel.query(). But it's also possible to callndb.Query().

Arguments

kind
Optional kind string. Normally, the name of a entity class.
ancestor
Optional ancestor Key.
filters
Optional Node representing a filter expression tree.
orders
Optionaldatastore_query.Order object.
app
Optional app id.
namespace
Optional namespace. If not specified, the default namespace at the time the query is executed will be used.
projection
Optional list or tuple of properties to project.
group_by
Optional list or tuple of properties to group by.
default_options
OptionalQueryOptions object giving default query options to be used when the query is executed.

Instance Methods

filter(filter1, filter2, ...)
Returns a newQuery with additional filter(s) applied. Takes filter arguments as described inQueries.qry.filter(filter1).filter(filter2) is equivalent toqry.filter(filter1filter2)
get(**q_options)
Returns the first query result, if any (otherwiseNone). This is similar to callingq.fetch(1) and returning the first item of the list of results.

Arguments

**q_options
Allquery options keyword arguments are supported.
order(order1,order2, ...)
Returns a newQuery with additional sort order(s) applied. Takes one or more arguments which are properties or "negated" properties. For example, to sort users by age and "break ties" by name, you might use something likeqry.order(-Account.birthday, Account.name)
bind(...values...)
This function is for use with GQL queries that use parameter bindings (:1,:2, etc.) or named bindings (:foo,:bar, etc.). It binds the passed values to the parameters.

To bind parameters, you might call something likeqry.bind("USA", 49). To bind named parameters, you might call something likeqry.bind(region = "USA", threshold = 49).

Returns a newQuery object with the parameter values bound.

count(limit=None,**q_options)
Returns the number of query results, up to a limit. This returns the same result aslen(q.fetch(limit)) but more efficiently.

Arguments

limit
How many results to count at most
**q_options
Allquery options keyword arguments andcontext options are supported.
count_async(limit,**q_options)
Asynchronously counts the number of query results, up to a limit; it returns aFuture whose result is a number. This is the asynchronous version ofcount().
fetch(limit,**q_options)
Fetch a list of query results, up to a limit.

Arguments

limit
How many results to count at most
**q_options
Allquery options keyword arguments are supported.
fetch_async(limit,**q_options)
Asynchronously fetch a list of query results, up to a limit. Returns aFuture whose result is a list of results. This is the asynchronous version offetch().
fetch_page(page_size,**q_options)
Fetch a "page" of results. This is a specialized method for use by paging user interfaces.

Arguments

page_size
At most this many results will be returned.
**q_options
Allquery options keyword arguments are supported.
Returns a tuple(results,cursor,more):
  • results list of query results
  • cursor aquery cursor pointing to the "next" batch of results. If there are no more results, this might beNone.
  • morebool indicating whether there are (likely) more results after this batch. IfFalse, there are no more results; ifTrue, there areprobably more results.

To fetch the next page, pass the cursor returned by one call to the next call usingstart_cursor=cursor. A common idiom is to pass the cursor to the client usingcursor.urlsafe() and to reconstruct that cursor on a subsequent request usingCursor(urlsafe=string).

fetch_page_async(page_size,**q_options)
Asynchronously fetch a "page" of results. This is the asynchronous version offetch_page().
get_async(**q_options)
Asynchronously returns the first query result, if any (otherwiseNone). This is the asynchronous version ofget().
iter(**q_options)
Constructs and returns an iterator over the query.

Arguments

**q_options
Allquery options keyword arguments are supported.

Returns aQueryIterator object.

map(callback,pass_batch_into_callback=None,merge_future=None,**q_options)
Map a callback function or tasklet over the query results. That is, apply the function (or tasklet) to each entity in the query results.

Arguments

callback
A function or tasklet to be applied to each result.
pass_batch_into_callback
IfTrue, calls the callback with batch information arguments as described below.
merge_future
OptionalFuture subclass; see below.
**q_options
Allquery options keyword arguments are supported.

Callback signature The callback is normally called with an entity as argument. However, ifkeys_only=True is given, it is called with aKey. Ifpass_batch_into_callback=True is given, the callback is called with three arguments: the current batch, the index within the batch, and the entity orKey at that index. The callback can return whatever it wants. If the callback isNone, a trivial callback is assumed that just returns the entity or key passed in.

Optionalmerge_future Themerge_future is an advanced argument that can be used to override how the callback results are combined into the overallmap() return value. By default, a list of callback return values is produced. By substituting one of a small number of specialized alternatives you can arrange otherwise. See the source code fortasklets.MultiFuture for the default implementation and a description of the protocol themerge_future object must implement. Alternatives from the same module includeQueueFuture,SerialQueueFuture andReducingFuture.

Returns a list of the results of all the callbacks. (But see 'optionalmerge_future' above.) It returns when the query has run to completion and all callbacks have returned.

map_async(callback,pass_batch_into_callback=None,merge_future=None,**q_options)
Asynchronously map a callback function or tasklet over the query results. This is the asynchronous version ofmap().

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.