Python

0.02.2

Queries#

Create / interact with gcloud datastore queries.

class gcloud.datastore.query.Query(kind=None, dataset=None, namespace=None)[source]#

Bases: object

A Query against the Cloud Datastore.

This class serves as an abstraction for creating a query over data stored in the Cloud Datastore.

Each Query object is immutable, and a clone is returned whenever any part of the query is modified:

>>> query = Query('MyKind')
>>> limited_query = query.limit(10)
>>> query.limit() == 10
False
>>> limited_query.limit() == 10
True

You typically won’t construct a Query by initializing it like Query('MyKind', dataset=...) but instead use the helper gcloud.datastore.dataset.Dataset.query() method which generates a query that can be executed without any additional work:

>>> from gcloud import datastore
>>> dataset = datastore.get_dataset('dataset-id', email, key_path)
>>> query = dataset.query('MyKind')
Parameters:
  • kind (string) – The kind to query.
  • dataset (gcloud.datastore.dataset.Dataset) – The dataset to query.
  • dataset – The namespace to which to restrict results.
OPERATORS = {'=': 5, '>=': 4, '<': 1, '>': 3, '<=': 2}#

Mapping of operator strings and their protobuf equivalents.

ancestor(ancestor)[source]#

Filter the query based on an ancestor.

This will return a clone of the current Query filtered by the ancestor provided.

For example:

>>> parent_key = Key.from_path('Person', '1')
>>> query = dataset.query('Person')
>>> filtered_query = query.ancestor(parent_key)

If you don’t have a gcloud.datastore.key.Key but just know the path, you can provide that as well:

>>> query = dataset.query('Person')
>>> filtered_query = query.ancestor(['Person', '1'])

Each call to .ancestor() returns a cloned Query, however a query may only have one ancestor at a time.

Parameters:ancestor (gcloud.datastore.key.Key or list) – Either a Key or a path of the form ['Kind', 'id or name', 'Kind', 'id or name', ...].
Return type:Query
Returns:A Query filtered by the ancestor provided.
cursor()[source]#

Returns cursor ID

Caution

Invoking this method on a query that has not yet been executed will raise a RuntimeError.

Return type:string
Returns:base64-encoded cursor ID string denoting the last position consumed in the query’s result set.
dataset(dataset=None)[source]#

Get or set the datastore.dataset.Dataset for this Query.

This is the dataset against which the Query will be run.

This is a hybrid getter / setter, used as:

>>> query = Query('Person')
>>> query = query.dataset(my_dataset)  # Set the dataset.
>>> query.dataset()  # Get the current dataset.
<Dataset object>
Return type:gcloud.datastore.dataset.Dataset, None, or Query
Returns:If no arguments, returns the current dataset. If a dataset is provided, returns a clone of the Query with that dataset set.
fetch(limit=None)[source]#

Executes the Query and returns all matching entities.

This makes an API call to the Cloud Datastore, sends the Query as a protobuf, parses the responses to Entity protobufs, and then converts them to gcloud.datastore.entity.Entity objects.

For example:

>>> from gcloud import datastore
>>> dataset = datastore.get_dataset('dataset-id', email, key_path)
>>> query = dataset.query('Person').filter('name =', 'Sally')
>>> query.fetch()
[<Entity object>, <Entity object>, ...]
>>> query.fetch(1)
[<Entity object>]
>>> query.limit()
None
Parameters:limit (integer) – An optional limit to apply temporarily to this query. That is, the Query itself won’t be altered, but the limit will be applied to the query before it is executed.
Return type:list of gcloud.datastore.entity.Entity‘s
Returns:The list of entities matching this query’s criteria.
filter(expression, value)[source]#

Filter the query based on an expression and a value.

This will return a clone of the current Query filtered by the expression and value provided.

Expressions take the form of:

.filter('<property> <operator>', <value>)

where property is a property stored on the entity in the datastore and operator is one of OPERATORS (ie, =, <, <=, >, >=):

>>> query = Query('Person')
>>> filtered_query = query.filter('name =', 'James')
>>> filtered_query = query.filter('age >', 50)

Because each call to .filter() returns a cloned Query object we are able to string these together:

>>> query = Query('Person').filter(
...     'name =', 'James').filter('age >', 50)
Parameters:
  • expression (string) – An expression of a property and an operator (ie, =).
  • value (integer, string, boolean, float, None, datetime) – The value to filter on.
Return type:

Query

Returns:

A Query filtered by the expression and value provided.

group_by(group_by=None)[source]#

Adds a group_by to the query.

This is a hybrid getter / setter, used as:

>>> query = Query('Person')
>>> query.group_by()  # Get the group_by for this query.
[]
>>> query = query.group_by(['name'])
>>> query.group_by()  # Get the group_by for this query.
['name']
Parameters:group_by (sequence of strings) – Each value is a string giving the name of a property to use to group results together.
Return type:Query or list of strings.
Returns:If no arguments, returns the current group_by. If a list of group by properties is provided, returns a clone of the Query with that list of values set.
kind(*kinds)[source]#

Get or set the Kind of the Query.

Note

This is an additive operation. That is, if the Query is set for kinds A and B, and you call .kind('C'), it will query for kinds A, B, and, C.

Parameters:kinds (string) – The entity kinds for which to query.
Return type:string or Query
Returns:If no arguments, returns the kind. If a kind is provided, returns a clone of the Query with those kinds set.
limit(limit=None)[source]#

Get or set the limit of the Query.

This is the maximum number of rows (Entities) to return for this Query.

This is a hybrid getter / setter, used as:

>>> query = Query('Person')
>>> query = query.limit(100)  # Set the limit to 100 rows.
>>> query.limit()  # Get the limit for this query.
100
Return type:integer, None, or Query
Returns:If no arguments, returns the current limit. If a limit is provided, returns a clone of the Query with that limit set.
namespace()[source]#

This query’s namespace

Return type:string or None
Returns:the namespace assigned to this query
offset(offset=None)[source]#

Adds offset to the query to allow pagination.

NOTE: Paging with cursors should be preferred to using an offset.

This is a hybrid getter / setter, used as:

>>> query = Query('Person')
>>> query.offset()  # Get the offset for this query.
0
>>> query = query.offset(10)
>>> query.offset()  # Get the offset for this query.
10
Parameters:offset (non-negative integer.) – Value representing where to start a query for a given kind.
Return type:Query or int.
Returns:If no arguments, returns the current offset. If an offset is provided, returns a clone of the Query with that offset set.
order(*properties)[source]#

Adds a sort order to the query.

Sort fields will be applied in the order specified.

Parameters:properties (sequence of strings) – Each value is a string giving the name of the property on which to sort, optionally preceded by a hyphen (-) to specify descending order. Omitting the hyphen implies ascending order.
Return type:Query
Returns:A new Query instance, ordered as specified.
projection(projection=None)[source]#

Adds a projection to the query.

This is a hybrid getter / setter, used as:

>>> query = Query('Person')
>>> query.projection()  # Get the projection for this query.
[]
>>> query = query.projection(['name'])
>>> query.projection()  # Get the projection for this query.
['name']
Parameters:projection (sequence of strings) – Each value is a string giving the name of a property to be included in the projection query.
Return type:Query or list of strings.
Returns:If no arguments, returns the current projection. If a projection is provided, returns a clone of the Query with that projection set.
to_protobuf()[source]#

Convert Query instance to datastore_v1_pb2.Query.

Return type:gcloud.datastore.datastore_v1_pb2.Query
Returns:A Query protobuf that can be sent to the protobuf API.
with_cursor(start_cursor, end_cursor=None)[source]#

Specifies the starting / ending positions in a query’s result set.

Parameters:
  • start_cursor (bytes) – Base64-encoded cursor string specifying where to start reading query results.
  • end_cursor (bytes) – Base64-encoded cursor string specifying where to stop reading query results.
Return type:

Query

Returns:

If neither cursor is passed, returns self; else, returns a clone of the Query, with cursors updated.