Queries

Classes for representing queries for the Google Cloud Firestore API.

A Query can be created directly from a Collection and that can be a more common way to create a query than direct usage of the constructor.

class google.cloud.firestore_v1.query.Query(parent, projection=None, field_filters=(), orders=(), limit=None, offset=None, start_at=None, end_at=None, all_descendants=False)

Bases: object

Represents a query to the Firestore API.

Instances of this class are considered immutable: all methods that would modify an instance instead return a new instance.

  • Parameters

    • parent (CollectionReference) – The collection that this query applies to.

    • projection (Optional[google.cloud.proto.firestore.v1. query_pb2.StructuredQuery.Projection]) – A projection of document fields to limit the query results to.

    • field_filters (Optional[Tuple[google.cloud.proto.firestore.v1. query_pb2.StructuredQuery.FieldFilter, …]]) – The filters to be applied in the query.

    • orders (Optional[Tuple[google.cloud.proto.firestore.v1. query_pb2.StructuredQuery.Order, …]]) – The “order by” entries to use in the query.

    • limit (Optional[int]) – The maximum number of documents the query is allowed to return.

    • offset (Optional[int]) – The number of results to skip.

    • start_at (Optional[Tuple[dict, *[bool](https://python.readthedocs.io/en/latest/library/functions.html#bool)]*]) – Two-tuple of :

      • a mapping of fields. Any field that is present in this mapping must also be present in orders

      • an after flag

      The fields and the flag combine to form a cursor used as a starting point in a query result set. If the after flag is True, the results will start just after any documents which have fields matching the cursor, otherwise any matching documents will be included in the result set. When the query is formed, the document values will be used in the order given by orders.

    • end_at (Optional[Tuple[dict, *[bool](https://python.readthedocs.io/en/latest/library/functions.html#bool)]*]) – Two-tuple of:

      • a mapping of fields. Any field that is present in this mapping must also be present in orders

      • a before flag

      The fields and the flag combine to form a cursor used as an ending point in a query result set. If the before flag is True, the results will end just before any documents which have fields matching the cursor, otherwise any matching documents will be included in the result set. When the query is formed, the document values will be used in the order given by orders.

    • all_descendants (Optional[bool]) – When false, selects only collections that are immediate children of the parent specified in the containing RunQueryRequest. When true, selects all descendant collections.

ASCENDING( = 'ASCENDING )

Sort query results in ascending order on a field.

DESCENDING( = 'DESCENDING )

Sort query results in descending order on a field.

end_at(document_fields)

End query results at a particular document value.

The result set will include the document specified by document_fields.

If the current query already has specified an end cursor – either via this method or end_before() – this will overwrite it.

When the query is sent to the server, the document_fields will be used in the order given by fields set by order_by().

  • Parameters

    document_fields – (Union[DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set.

  • Returns

    A query with cursor. Acts as a copy of the current query, modified with the newly added “end at” cursor.

  • Return type

    Query

end_before(document_fields)

End query results before a particular document value.

The result set will exclude the document specified by document_fields.

If the current query already has specified an end cursor – either via this method or end_at() – this will overwrite it.

When the query is sent to the server, the document_fields will be used in the order given by fields set by order_by().

  • Parameters

    document_fields – (Union[DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set.

  • Returns

    A query with cursor. Acts as a copy of the current query, modified with the newly added “end before” cursor.

  • Return type

    Query

get(transaction=None)

Deprecated alias for stream().

limit(count)

Limit a query to return a fixed number of results.

If the current query already has a limit set, this will overwrite it.

  • Parameters

    count (int) – Maximum number of documents to return that match the query.

  • Returns

    A limited query. Acts as a copy of the current query, modified with the newly added “limit” filter.

  • Return type

    Query

offset(num_to_skip)

Skip to an offset in a query.

If the current query already has specified an offset, this will overwrite it.

  • Parameters

    num_to_skip (int) – The number of results to skip at the beginning of query results. (Must be non-negative.)

  • Returns

    An offset query. Acts as a copy of the current query, modified with the newly added “offset” field.

  • Return type

    Query

on_snapshot(callback)

Monitor the documents in this collection that match this query.

This starts a watch on this query using a background thread. The provided callback is run on the snapshot of the documents.

  • Parameters

    callback (Callable[[QuerySnapshot], NoneType]) – a callback to run when a change occurs.

Example:

from google.cloud import firestore_v1

db = firestore_v1.Client()
query_ref = db.collection(u'users').where("user", "==", u'Ada')

def on_snapshot(docs, changes, read_time):
    for doc in docs:
        print(u'{} => {}'.format(doc.id, doc.to_dict()))

# Watch this query
query_watch = query_ref.on_snapshot(on_snapshot)

# Terminate this watch
query_watch.unsubscribe()

order_by(field_path, direction='ASCENDING')

Modify the query to add an order clause on a specific field.

See field_path() for more information on field paths.

Successive order_by() calls will further refine the ordering of results returned by the query (i.e. the new “order by” fields will be added to existing ones).

  • Parameters

    • field_path (str) – A field path (.-delimited list of field names) on which to order the query results.

    • direction (Optional[str]) – The direction to order by. Must be one of ASCENDING or DESCENDING, defaults to ASCENDING.

  • Returns

    An ordered query. Acts as a copy of the current query, modified with the newly added “order by” constraint.

  • Return type

    Query

  • Raises

    • ValueError – If field_path is invalid.

    • ValueError – If direction is not one of ASCENDING or DESCENDING.

select(field_paths)

Project documents matching query to a limited set of fields.

See field_path() for more information on field paths.

If the current query already has a projection set (i.e. has already called select()), this will overwrite it.

  • Parameters

    field_paths (Iterable[str, **...]) – An iterable of field paths (.-delimited list of field names) to use as a projection of document fields in the query results.

  • Returns

    A “projected” query. Acts as a copy of the current query, modified with the newly added projection.

  • Return type

    Query

  • Raises

    ValueError – If any field_path is invalid.

start_after(document_fields)

Start query results after a particular document value.

The result set will exclude the document specified by document_fields.

If the current query already has specified a start cursor – either via this method or start_at() – this will overwrite it.

When the query is sent to the server, the document_fields will be used in the order given by fields set by order_by().

  • Parameters

    document_fields – (Union[DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set.

  • Returns

    A query with cursor. Acts as a copy of the current query, modified with the newly added “start after” cursor.

  • Return type

    Query

start_at(document_fields)

Start query results at a particular document value.

The result set will include the document specified by document_fields.

If the current query already has specified a start cursor – either via this method or start_after() – this will overwrite it.

When the query is sent to the server, the document_fields will be used in the order given by fields set by order_by().

  • Parameters

    document_fields – (Union[DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set.

  • Returns

    A query with cursor. Acts as a copy of the current query, modified with the newly added “start at” cursor.

  • Return type

    Query

stream(transaction=None)

Read the documents in the collection that match this query.

This sends a RunQuery RPC and then returns an iterator which consumes each document returned in the stream of RunQueryResponse messages.

NOTE: The underlying stream of responses will time out after the max_rpc_timeout_millis value set in the GAPIC client configuration for the RunQuery API. Snapshots not consumed from the iterator before that point will be lost.

If a transaction is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed).

  • Parameters

    transaction – (Optional[Transaction]): An existing transaction that this query will run in.

  • Yields

    DocumentSnapshot – The next document that fulfills the query.

where(field_path, op_string, value)

Filter the query on a field.

See field_path() for more information on field paths.

Returns a new Query that filters on a specific field path, according to an operation (e.g. == or “equals”) and a particular value to be paired with that operation.

  • Parameters

    • field_path (str) – A field path (.-delimited list of field names) for the field to filter on.

    • op_string (str) – A comparison operation in the form of a string. Acceptable values are <, <=, ==, >= and >.

    • value (Any) – The value to compare the field against in the filter. If value is None or a NaN, then == is the only allowed operation.

  • Returns

    A filtered query. Acts as a copy of the current query, modified with the newly added filter.

  • Return type

    Query

  • Raises