Stay organized with collections Save and categorize content based on your preferences.
Note: Developers building new applications are strongly encouraged to use the NDB Client Library, which has several benefits compared to this client library, such as automatic entity caching via the Memcache API. If you are currently using the older DB Client Library, read the DB to NDB Migration Guide
Class GqlQuery
represents a query for retrieving entities from the App Engine Datastore using the SQL-like App Engine query language, GQL. For a complete discussion of GQL syntax and features, see the GQL Reference; see also the related class Query
, which uses objects and methods, rather than GQL, to prepare queries.
GqlQuery
is defined in the module google.appengine.ext.db
.
Note: The index-based query mechanism supports a wide range of queries and is suitable for most applications. However, it does not support some kinds of query common in other database technologies: in particular, joins and aggregate queries aren't supported within the Datastore query engine. See Datastore Queries page for limitations on Datastore queries.
IntroductionAn application creates a GQL query object by calling either the GqlQuery
constructor directly or the class method gql()
of an entity kind's model class. The GqlQuery
constructor takes as an argument a query string, a complete GQL statement beginning with SELECT
...
FROM
model-name
. Values in WHERE
clauses can be numeric or string literals, or can use parameter binding for values. Parameters can be bound using either positional or keyword arguments:
q = GqlQuery("SELECT * FROM Song WHERE composer = 'Lennon, John'") q = GqlQuery("SELECT __key__ FROM Song WHERE composer = :1", "Lennon, John") q = GqlQuery("SELECT * FROM Song WHERE composer = :composer", composer="Lennon, John")
For convenience, the Model
and Expando
classes have a class method gql()
that returns a GqlQuery
instance. This method takes a GQL query string without the SELECT
...
FROM
model-name
prefix, which is implied:
q = Song.gql("WHERE composer = 'Lennon, John'")
The application can then execute the query and access the results in any of the following ways:
Treat the query object as an iterable, to process matching entities one at a time:
for song in q: print song.title
This implicitly calls the query's run()
method to generate the matching entities. It is thus equivalent to
for song in q.run(): print song.title
You can set a limit on the number of results to process with the keyword argument limit
:
for song in q.run(limit=5): print song.title
The iterator interface does not cache results, so creating a new iterator from the query object reiterates the same query from the beginning.
Call the query's get()
method, to obtain the first single matching entity found in the Datastore:
song = q.get() print song.title
Call the query's fetch()
method, to obtain a list of all matching entities up to a specified number of results:
results = q.fetch(limit=5) for song in results: print song.title
As with run()
, the query object does not cache results, so calling fetch()
a second time reissues the same query.
Note: You should rarely need to use this method; it is almost always better to use run()
instead.
The constructor for class GqlQuery
is defined as follows:
Creates an instance of class GqlQuery
for retrieving entities from the App Engine Datastore using the GQL query language.
Arguments
Instances of class GqlQuery
have the following methods:
Rebinds the query's parameter values. The modified query will be executed the first time results are accessed after its parameters have been rebound.
Rebinding parameters to an existing GqlQuery
object is faster than building a new GqlQuery
object, because the query string doesn't need to be parsed again.
Arguments
Returns the tuple of properties in the projection or None
.
Returns a boolean value indicating whether the query is a keys-only query.
Returns an iterable for looping over the results of the query. This allows you to specify the query's operation with parameter settings and access the results iteratively:
offset
argument.limit
argument.The loop's performance thus scales linearly with the sum of offset
+ limit
. If you know how many results you want to retrieve, you should always set an explicit limit
value.
This method uses asynchronous prefetching to improve performance. By default, it retrieves its results from the Datastore in small batches, allowing the application to stop the iteration and avoid retrieving more results than are needed.
Tip: To retrieve all available results when their number is unknown, set batch_size
to a large value, such as 1000
.
Tip: If you don't need to change the default argument values, you can just use the query object directly as an iterable to control the loop. This implicitly calls run()
with default arguments.
Arguments
Note: Global (non-ancestor) queries ignore this argument.
LIMIT
clause of the GQL query string will be used. If explicitly set to None
, all available results will be retrieved.
limit
is set, defaults to the specified limit; otherwise defaults to 20
.
true
, return only keys instead of complete entities. Keys-only queries are faster and cheaper than those that return complete entities.
Note: Specifying this parameter may change the query's index requirements.
Executes the query and returns the first result, or None
if no results are found. At most one result is retrieved from the Datastore; the LIMIT
clause of the GQL query string, if any, is ignored.
Arguments
Note: Global (non-ancestor) queries ignore this argument.
true
, return only keys instead of complete entities. Keys-only queries are faster and cheaper than those that return complete entities.
Note: Specifying this parameter may change the query's index requirements.
Executes the query and returns a (possibly empty) list of results:
offset
argument.limit
argument.The method's performance thus scales linearly with the sum of offset
+ limit
.
Note: This method is merely a thin wrapper around the run()
method, and is less efficient and more memory-intensive than using run()
directly. You should rarely need to use fetch()
; it is provided mainly for convenience in cases where you need to retrieve a full in-memory list of query results.
Tip: The fetch()
method is designed to retrieve only the number of results specified by the limit
argument. To retrieve all available results of a query when their number is unknown, use run()
with a large batch size, such as run(batch_size=1000)
, instead of fetch()
.
Arguments
None
, all available results will be retrieved.
Note: Global (non-ancestor) queries ignore this argument.
true
, return only keys instead of complete entities. Keys-only queries are faster and cheaper than those that return complete entities.
Note: Specifying this parameter may change the query's index requirements.
Returns the number of results matching the query. This is faster by a constant factor than actually retrieving all of the results, but the running time still scales linearly with the sum of offset
+ limit
. Unless the result count is expected to be small, it is best to specify a limit
argument; otherwise the method will continue until it finishes counting or times out.
Arguments
Note: Global (non-ancestor) queries ignore this argument.
Note: If specified explicitly, this parameter overrides any value set in the LIMIT
clause of the GQL query string. However, if the parameter is omitted, the default value of 1000
does not override the GQL query's LIMIT
clause and applies only if no LIMIT
clause has been specified.
Returns a list of indexes used by an executed query, including primary, composite, kind, and single-property indexes.
Caution: Invoking this method on a query that has not yet been executed will raise an AssertionError
exception.
Note: This feature is not fully supported on the development server. When used with the development server, the result is either the empty list or a list containing exactly one composite index.
For example, the following code prints various information about the indexes used by a query:
# other imports ... import webapp2 from google.appengine.api import users from google.appengine.ext import db class Greeting(db.Model): author = db.StringProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class MainPage(webapp2.RequestHandler): def get(self): user = users.get_current_user() q = db.GqlQuery(Greeting) q.filter("author =", user.user_id()) q.order("-date") q.fetch(100) index_list = q.index_list() for ix in index_list: self.response.out.write("Kind: %s" % ix.kind()) self.response.out.write("<br />") self.response.out.write("Has ancestor? %s" % ix.has_ancestor()) self.response.out.write("<br />") for name, direction in ix.properties(): self.response.out.write("Property name: "+name) self.response.out.write("<br />") if direction == db.Index.DESCENDING: self.response.out.write("Sort direction: DESCENDING") else: self.response.out.write("Sort direction: ASCENDING") self.response.out.write("<br />")
This produces output like the following for each index:
Kind: Greeting Has ancestor? False Property name: author Sort direction: ASCENDING Property name: date Sort direction: DESCENDING
Returns a base64-encoded cursor string denoting the position in the query's result set following the last result retrieved. The cursor string is safe to use in HTTP GET
and POST
parameters, and can also be stored in the Datastore or Memcache. A future invocation of the same query can provide this string via the start_cursor
parameter or the with_cursor()
method to resume retrieving results from this position.
Caution: Invoking this method on a query that has not yet been executed will raise an AssertionError
exception.
Note: Not all queries are compatible with cursors; see the Datastore Queries page for more information.
Specifies the starting and (optionally) ending positions within a query's result set from which to retrieve results. The cursor strings denoting the starting and ending positions can be obtained by calling cursor()
after a previous invocation of the query. The current query must be identical to that earlier invocation, including the entity kind, property filters, ancestor filters, and sort orders.
Arguments
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-08-07 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-07 UTC."],[[["Developers should consider using the NDB Client Library for new applications due to its benefits like automatic entity caching through the Memcache API."],["The `GqlQuery` class allows querying the App Engine Datastore using GQL, a SQL-like query language, and can be created directly or via the `gql()` method of entity model classes."],["`GqlQuery` objects support various methods like `run()`, `get()`, and `fetch()` for executing queries and accessing results, with `run()` being the preferred method for iterative processing, while `fetch()` is mainly for retrieving a full list of results in memory."],["The `run()`, `get()`, and `fetch()` instance methods all support options for read policy, deadline, offset, keys only, and projection, to fine-tune the query's behavior and efficiency."],["The `GqlQuery` object also offers advanced features such as parameter rebinding via `bind()`, cursor management with `cursor()` and `with_cursor()`, and index analysis via `index_list()`."]]],[]]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4