As of January 1, 2020 this library no longer supports Python 2 on the latest released version. Library versions released prior to that date will continue to be available. For more information please visit Python 2 support on Google Cloud.

Collections

Classes for representing collections for the Google Cloud Firestore API.

class google.cloud.firestore_v1.base_collection.BaseCollectionReference(*path, **kwargs)[source]

Bases: Generic[google.cloud.firestore_v1.base_query.QueryType]

A reference to a collection in a Firestore database.

The collection may already exist or this class can facilitate creation of documents within the collection.

Parameters
  • path (Tuple[str, ...]) – The components in the collection path. This is a series of strings representing each collection and sub-collection ID, as well as the document IDs for any documents that contain a sub-collection.

  • kwargs (dict) – The keyword arguments for the constructor. The only supported keyword is client and it must be a Client if provided. It represents the client that created this collection reference.

Raises
  • ValueError – if * the path is empty * there are an even number of elements * a collection ID in path is not a string * a document ID in path is not a string

  • TypeError – If a keyword other than client is used.

avg(field_ref: str | FieldPath, alias=None)[source]

Adds an avg over the nested query.

Parameters
  • field_ref (Union[str, google.cloud.firestore_v1.field_path.FieldPath]) – The field to aggregate across.

  • alias (Optional[str]) – Optional name of the field to store the result of the aggregation into. If not provided, Firestore will pick a default name following the format field_<incremental_id++>.

count(alias=None)[source]

Adds a count over the nested query.

Parameters

alias (str) – (Optional) The alias for the count

document(document_id: Optional[str] = None) google.cloud.firestore_v1.document.DocumentReference[source]

Create a sub-document underneath the current collection.

Parameters

document_id (Optional[str]) – The document identifier within the current collection. If not provided, will default to a random 20 character string composed of digits, uppercase and lowercase and letters.

Returns

The child document.

Return type

DocumentReference

end_at(document_fields: Union[DocumentSnapshot, dict, list, tuple]) QueryType[source]

End query at a cursor with this collection as parent.

See end_at() for more information on this method.

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.

Return type

Query

end_before(document_fields: Union[DocumentSnapshot, dict, list, tuple]) QueryType[source]

End query before a cursor with this collection as parent.

See end_before() for more information on this method.

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.

Return type

Query

property id

The collection identifier.

Returns

The last component of the path.

Return type

str

limit(count: int) google.cloud.firestore_v1.base_query.QueryType[source]

Create a limited query with this collection as parent.

Note

limit and limit_to_last are mutually exclusive. Setting limit will drop previously set limit_to_last.

See limit() for more information on this method.

Parameters

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

Returns

A limited query.

Return type

Query

limit_to_last(count: int)[source]

Create a limited to last query with this collection as parent.

Note

limit and limit_to_last are mutually exclusive. Setting limit_to_last will drop previously set limit.

See limit_to_last() for more information on this method.

Parameters

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

Returns

A limited to last query.

Return type

Query

offset(num_to_skip: int) google.cloud.firestore_v1.base_query.QueryType[source]

Skip to an offset in a query with this collection as parent.

See offset() for more information on this method.

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.

Return type

Query

order_by(field_path: str, **kwargs) google.cloud.firestore_v1.base_query.QueryType[source]

Create an “order by” query with this collection as parent.

See order_by() for more information on this method.

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

  • kwargs (Dict[str, Any]) – The keyword arguments to pass along to the query. The only supported keyword is direction, see order_by() for more information.

Returns

An “order by” query.

Return type

Query

property parent

Document that owns the current collection.

Returns

The parent document, if the current collection is not a top-level collection.

Return type

Optional[DocumentReference]

select(field_paths: Iterable[str]) google.cloud.firestore_v1.base_query.QueryType[source]

Create a “select” query with this collection as parent.

See select() for more information on this method.

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.

Return type

Query

start_after(document_fields: Union[DocumentSnapshot, dict, list, tuple]) QueryType[source]

Start query after a cursor with this collection as parent.

See start_after() for more information on this method.

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.

Return type

Query

start_at(document_fields: Union[DocumentSnapshot, dict, list, tuple]) QueryType[source]

Start query at a cursor with this collection as parent.

See start_at() for more information on this method.

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.

Return type

Query

sum(field_ref: str | FieldPath, alias=None)[source]

Adds a sum over the nested query.

Parameters
  • field_ref (Union[str, google.cloud.firestore_v1.field_path.FieldPath]) – The field to aggregate across.

  • alias (Optional[str]) – Optional name of the field to store the result of the aggregation into. If not provided, Firestore will pick a default name following the format field_<incremental_id++>.

where(field_path: Optional[str] = None, op_string: Optional[str] = None, value=None, *, filter=None) google.cloud.firestore_v1.base_query.QueryType[source]

Create a “where” query with this collection as parent.

See where() for more information on this method.

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

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

  • 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. If op_string is in, value must be a sequence of values. Optional.

  • (class (filter) – ~google.cloud.firestore_v1.base_query.BaseFilter): an instance of a Filter. Either a FieldFilter or a CompositeFilter.

Returns

A filtered query.

Return type

Query

Raises

ValueError, if both the positional arguments (field_path, op_string, value) – and the filter keyword argument are passed at the same time.

Classes for representing collections for the Google Cloud Firestore API.

class google.cloud.firestore_v1.collection.CollectionReference(*path, **kwargs)[source]

Bases: google.cloud.firestore_v1.base_collection.BaseCollectionReference[google.cloud.firestore_v1.query.Query]

A reference to a collection in a Firestore database.

The collection may already exist or this class can facilitate creation of documents within the collection.

Parameters
  • path (Tuple[str, ...]) – The components in the collection path. This is a series of strings representing each collection and sub-collection ID, as well as the document IDs for any documents that contain a sub-collection.

  • kwargs (dict) – The keyword arguments for the constructor. The only supported keyword is client and it must be a Client if provided. It represents the client that created this collection reference.

Raises
  • ValueError – if * the path is empty * there are an even number of elements * a collection ID in path is not a string * a document ID in path is not a string

  • TypeError – If a keyword other than client is used.

add(document_data: dict, document_id: Optional[str] = None, retry: google.api_core.retry.retry_unary.Retry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None) Tuple[Any, Any][source]

Create a document in the Firestore database with the provided data.

Parameters
  • document_data (dict) – Property names and values to use for creating the document.

  • document_id (Optional[str]) – The document identifier within the current collection. If not provided, an ID will be automatically assigned by the server (the assigned ID will be a random 20 character string composed of digits, uppercase and lowercase letters).

  • 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

Pair of

  • The update_time when the document was created/overwritten.

  • A document reference for the created document.

Return type

Tuple[google.protobuf.timestamp_pb2.Timestamp, DocumentReference]

Raises

google.cloud.exceptions.Conflict – If document_id is provided and the document already exists.

get(transaction: Optional[google.cloud.firestore_v1.transaction.Transaction] = None, retry: google.api_core.retry.retry_unary.Retry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None) list[source]

Read the documents in this collection.

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 this collection that match the query.

Return type

list

list_documents(page_size: Optional[int] = None, retry: google.api_core.retry.retry_unary.Retry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None) Generator[Any, Any, None][source]

List all subdocuments of the current collection.

Parameters
  • page_size (Optional[int]]) – The maximum number of documents in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API.

  • 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

iterator of subdocuments of the current collection. If the collection does not exist at the time of snapshot, the iterator will be empty

Return type

Sequence[DocumentReference]

on_snapshot(callback: Callable) google.cloud.firestore_v1.watch.Watch[source]

Monitor the documents in this collection.

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

Parameters

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

Example

from google.cloud import firestore_v1

db = firestore_v1.Client() collection_ref = db.collection(u’users’)

def on_snapshot(collection_snapshot, changes, read_time):
for doc in collection_snapshot.documents:

print(u’{} => {}’.format(doc.id, doc.to_dict()))

# Watch this collection collection_watch = collection_ref.on_snapshot(on_snapshot)

# Terminate this watch collection_watch.unsubscribe()

stream(transaction: Optional[google.cloud.firestore_v1.transaction.Transaction] = None, retry: google.api_core.retry.retry_unary.Retry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None) Generator[google.cloud.firestore_v1.base_document.DocumentSnapshot, Any, None][source]

Read the documents in this collection.

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 the 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 collections for the Google Cloud Firestore API.

class google.cloud.firestore_v1.async_collection.AsyncCollectionReference(*path, **kwargs)[source]

Bases: google.cloud.firestore_v1.base_collection.BaseCollectionReference[google.cloud.firestore_v1.async_query.AsyncQuery]

A reference to a collection in a Firestore database.

The collection may already exist or this class can facilitate creation of documents within the collection.

Parameters
  • path (Tuple[str, ...]) – The components in the collection path. This is a series of strings representing each collection and sub-collection ID, as well as the document IDs for any documents that contain a sub-collection.

  • kwargs (dict) – The keyword arguments for the constructor. The only supported keyword is client and it must be a Client if provided. It represents the client that created this collection reference.

Raises
  • ValueError – if * the path is empty * there are an even number of elements * a collection ID in path is not a string * a document ID in path is not a string

  • TypeError – If a keyword other than client is used.

async add(document_data: dict, document_id: Optional[str] = None, retry: google.api_core.retry.retry_unary_async.AsyncRetry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None) Tuple[Any, Any][source]

Create a document in the Firestore database with the provided data.

Parameters
  • document_data (dict) – Property names and values to use for creating the document.

  • document_id (Optional[str]) – The document identifier within the current collection. If not provided, an ID will be automatically assigned by the server (the assigned ID will be a random 20 character string composed of digits, uppercase and lowercase letters).

  • 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

Pair of

  • The update_time when the document was created/overwritten.

  • A document reference for the created document.

Return type

Tuple[google.protobuf.timestamp_pb2.Timestamp, AsyncDocumentReference]

Raises

google.cloud.exceptions.Conflict – If document_id is provided and the document already exists.

document(document_id: Optional[str] = None) google.cloud.firestore_v1.async_document.AsyncDocumentReference[source]

Create a sub-document underneath the current collection.

Parameters

document_id (Optional[str]) – The document identifier within the current collection. If not provided, will default to a random 20 character string composed of digits, uppercase and lowercase and letters.

Returns

The child document.

Return type

AsyncDocumentReference

async get(transaction: Optional[google.cloud.firestore_v1.transaction.Transaction] = None, retry: google.api_core.retry.retry_unary_async.AsyncRetry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None) list[source]

Read the documents in this collection.

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 this collection that match the query.

Return type

list

async list_documents(page_size: Optional[int] = None, retry: google.api_core.retry.retry_unary_async.AsyncRetry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None) AsyncGenerator[google.cloud.firestore_v1.document.DocumentReference, None][source]

List all subdocuments of the current collection.

Parameters
  • page_size (Optional[int]]) – The maximum number of documents in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API.

  • 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

iterator of subdocuments of the current collection. If the collection does not exist at the time of snapshot, the iterator will be empty

Return type

Sequence[DocumentReference]

async stream(transaction: Optional[google.cloud.firestore_v1.transaction.Transaction] = None, retry: google.api_core.retry.retry_unary_async.AsyncRetry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None) AsyncIterator[google.cloud.firestore_v1.base_document.DocumentSnapshot][source]

Read the documents in this collection.

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 the 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.