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.base_query.BaseCollectionGroup(parent, projection=None, field_filters=(), orders=(), limit=None, limit_to_last=False, offset=None, start_at=None, end_at=None, all_descendants=True, recursive=False)
Bases: google.cloud.firestore_v1.base_query.BaseQuery
Represents a Collection Group in the Firestore API.
This is a specialization of Query
that includes all documents in the
database that are contained in a collection or subcollection of the given
parent.
Parameters
parent (
CollectionReference
) – The collection that this query applies to.
class google.cloud.firestore_v1.base_query.BaseQuery(parent, projection=None, field_filters=(), orders=(), limit=None, limit_to_last=False, offset=None, start_at=None, end_at=None, all_descendants=False, recursive=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.StructuredQuery.Projection
]) – A projection of document fields to limit the query results to.field_filters (Optional[Tuple[
google.cloud.proto.firestore.v1. query.StructuredQuery.FieldFilter
, …]]) – The filters to be applied in the query.orders (Optional[Tuple[
google.cloud.proto.firestore.v1. query.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.
limit_to_last (Optional[bool]) – Denotes whether a provided limit is applied to the end of the result set.
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 isTrue
, 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 byorders
.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 isTrue
, 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 byorders
.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.
recursive (Optional[bool]) – When true, returns all documents and all documents in any subcollections below them. Defaults to false.
ASCENDING( = 'ASCENDING )
Sort query results in ascending order on a field.
Type
DESCENDING( = 'DESCENDING )
Sort query results in descending order on a field.
Type
end_at(document_fields_or_snapshot: Union[google.cloud.firestore_v1.base_document.DocumentSnapshot, dict, list, tuple])
End query results at a particular document value.
The result set will include the document specified by
document_fields_or_snapshot
.
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_or_snapshot
will
be used in the order given by fields set by
order_by()
.
Parameters
document_fields_or_snapshot – (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_or_snapshot: Union[google.cloud.firestore_v1.base_document.DocumentSnapshot, dict, list, tuple])
End query results before a particular document value.
The result set will exclude the document specified by
document_fields_or_snapshot
.
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_or_snapshot
will
be used in the order given by fields set by
order_by()
.
Parameters
document_fields_or_snapshot – (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
limit(count: int)
Limit a query to return at most count matching results.
If the current query already has a limit set, this will override it.
NOTE: limit and limit_to_last are mutually exclusive. Setting limit will drop previously set limit_to_last.
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
limit_to_last(count: int)
Limit a query to return the last count matching results. If the current query already has a limit_to_last set, this will override it.
NOTE: limit and limit_to_last are mutually exclusive. Setting limit_to_last will drop previously set limit.
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: int)
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
order_by(field_path: str, direction: str = '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
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 ofASCENDING
orDESCENDING
.
recursive()
Returns a copy of this query whose iterator will yield all matching documents as well as each of their descendent subcollections and documents.
This differs from the all_descendents flag, which only returns descendents whose subcollection names match the parent collection’s name. To return all descendents, regardless of their subcollection name, use this.
select(field_paths: Iterable[str])
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_or_snapshot: Union[google.cloud.firestore_v1.base_document.DocumentSnapshot, dict, list, tuple])
Start query results after a particular document value.
The result set will exclude the document specified by
document_fields_or_snapshot
.
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_or_snapshot
will
be used in the order given by fields set by
order_by()
.
Parameters
document_fields_or_snapshot – (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_or_snapshot: Union[google.cloud.firestore_v1.base_document.DocumentSnapshot, dict, list, tuple])
Start query results at a particular document value.
The result set will include the document specified by
document_fields_or_snapshot
.
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_or_snapshot – (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
where(field_path: str, op_string: str, 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
<
,<=
,==
,!=
,>=
,>
,in
,not-in
,array_contains
andarray_contains_any
.value (Any) – The value to compare the field against in the filter. If
value
isNone
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
ValueError – If
field_path
is invalid.ValueError – If
value
is a NaN orNone
andop_string
is not==
.
class google.cloud.firestore_v1.base_query.QueryPartition(query, start_at, end_at)
Bases: object
Represents a bounded partition of a collection group query.
Contains cursors that can be used in a query as a starting and/or end point for the collection group query. The cursors may only be used in a query that matches the constraints of the query that produced this partition.
Parameters
query (BaseQuery) – The original query that this is a partition of.
start_at (Optional[DocumentSnapshot]) – Cursor for first query result to include. If None, the partition starts at the beginning of the result set.
end_at (Optional[DocumentSnapshot]) – Cursor for first query result after the last result included in the partition. If None, the partition runs to the end of the result set.
query()
Generate a new query using this partition’s bounds.
Returns
Copy of the original query with start and end bounds set by the
cursors from this partition.
Return type
BaseQuery
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.CollectionGroup(parent, projection=None, field_filters=(), orders=(), limit=None, limit_to_last=False, offset=None, start_at=None, end_at=None, all_descendants=True, recursive=False)
Bases: google.cloud.firestore_v1.query.Query
, google.cloud.firestore_v1.base_query.BaseCollectionGroup
Represents a Collection Group in the Firestore API.
This is a specialization of Query
that includes all documents in the
database that are contained in a collection or subcollection of the given
parent.
Parameters
parent (
CollectionReference
) – The collection that this query applies to.
get_partitions(partition_count, retry: google.api_core.retry.Retry = <_MethodDefault._DEFAULT_VALUE:
Partition a query for parallelization.
Partitions a query by returning partition cursors that can be used to run the query in parallel. The returned partition cursors are split points that can be used as starting/end points for the query results.
Parameters
partition_count (int) – The desired maximum number of partition points. The number must be strictly positive. The actual number of partitions returned may be fewer.
retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried. Defaults to a system-specified policy.
timeout (float) – The timeout for this request. Defaults to a system-specified value.
class google.cloud.firestore_v1.query.Query(parent, projection=None, field_filters=(), orders=(), limit=None, limit_to_last=False, offset=None, start_at=None, end_at=None, all_descendants=False, recursive=False)
Bases: google.cloud.firestore_v1.base_query.BaseQuery
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.StructuredQuery.Projection
]) – A projection of document fields to limit the query results to.field_filters (Optional[Tuple[
google.cloud.proto.firestore.v1. query.StructuredQuery.FieldFilter
, …]]) – The filters to be applied in the query.orders (Optional[Tuple[
google.cloud.proto.firestore.v1. query.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 isTrue
, 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 byorders
.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 isTrue
, 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 byorders
.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.
count(alias: str | None = None)
Adds a count over the query.
Parameters
alias (str) – (Optional) The alias for the count
get(transaction=None, retry: google.api_core.retry.Retry = <_MethodDefault._DEFAULT_VALUE:
Read the documents in the collection that match this query.
This sends a RunQuery
RPC and returns a list of documents
returned in the stream of RunQueryResponse
messages.
Parameters
transaction – (Optional[
Transaction
]): An existing transaction that this query will run in. If atransaction
is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed).retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried. Defaults to a system-specified policy.
timeout (float) – The timeout for this request. Defaults to a system-specified value.
Returns
The documents in the collection that match this query.
Return type
on_snapshot(callback: Callable)
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()
stream(transaction=None, retry: google.api_core.retry.Retry = <_MethodDefault._DEFAULT_VALUE:
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.retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried. Defaults to a system-specified policy.
timeout (float) – The timeout for this request. Defaults to a system-specified value.
Yields
DocumentSnapshot
– The next document that fulfills the query.
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.async_query.AsyncCollectionGroup(parent, projection=None, field_filters=(), orders=(), limit=None, limit_to_last=False, offset=None, start_at=None, end_at=None, all_descendants=True, recursive=False)
Bases: google.cloud.firestore_v1.async_query.AsyncQuery
, google.cloud.firestore_v1.base_query.BaseCollectionGroup
Represents a Collection Group in the Firestore API.
This is a specialization of AsyncQuery
that includes all documents in the
database that are contained in a collection or subcollection of the given
parent.
Parameters
parent (
CollectionReference
) – The collection that this query applies to.
get_partitions(partition_count, retry: google.api_core.retry.Retry = <_MethodDefault._DEFAULT_VALUE:
Partition a query for parallelization.
Partitions a query by returning partition cursors that can be used to run the query in parallel. The returned partition cursors are split points that can be used as starting/end points for the query results.
Parameters
partition_count (int) – The desired maximum number of partition points. The number must be strictly positive. The actual number of partitions returned may be fewer.
retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried. Defaults to a system-specified policy.
timeout (float) – The timeout for this request. Defaults to a system-specified value.
class google.cloud.firestore_v1.async_query.AsyncQuery(parent, projection=None, field_filters=(), orders=(), limit=None, limit_to_last=False, offset=None, start_at=None, end_at=None, all_descendants=False, recursive=False)
Bases: google.cloud.firestore_v1.base_query.BaseQuery
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.StructuredQuery.Projection
]) – A projection of document fields to limit the query results to.field_filters (Optional[Tuple[
google.cloud.proto.firestore.v1. query.StructuredQuery.FieldFilter
, …]]) – The filters to be applied in the query.orders (Optional[Tuple[
google.cloud.proto.firestore.v1. query.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 isTrue
, 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 byorders
.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 isTrue
, 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 byorders
.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.
recursive (Optional[bool]) – When true, returns all documents and all documents in any subcollections below them. Defaults to false.
count(alias: str | None = None)
Adds a count over the nested query.
Parameters
alias – (Optional[str]): The alias for the count
Returns
An instance of an AsyncAggregationQuery object
Return type
async get(transaction: Optional[google.cloud.firestore_v1.transaction.Transaction] = None, retry: google.api_core.retry.Retry = <_MethodDefault._DEFAULT_VALUE:
Read the documents in the collection that match this query.
This sends a RunQuery
RPC and returns a list of documents
returned in the stream of RunQueryResponse
messages.
Parameters
transaction – (Optional[
Transaction
]): An existing transaction that this query will run in.retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried. Defaults to a system-specified policy.
timeout (float) – The timeout for this request. Defaults to a system-specified value.
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).
Returns
The documents in the collection that match this query.
Return type
stream(transaction=None, retry: google.api_core.retry.Retry = <_MethodDefault._DEFAULT_VALUE:
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.retry (google.api_core.retry.Retry) – Designation of what errors, if any, should be retried. Defaults to a system-specified policy.
timeout (float) – The timeout for this request. Defaults to a system-specified value.
Yields
DocumentSnapshot
– The next document that fulfills the query.