google.cloud.firestore module

Python idiomatic client for Google Cloud Firestore.

Exceptions

exception google.cloud.firestore.ReadAfterWriteError

Bases: exceptions.Exception

Raised when a read is attempted after a write.

Raised by “read” methods that use transactions.

Classes

class google.cloud.firestore.Client(project=None, credentials=None, database='(default)')

Bases: google.cloud.client.ClientWithProject

Client for interacting with Google Cloud Firestore API.

Parameters:
  • project (Optional[str]) – The project which the client acts on behalf of. If not passed, falls back to the default inferred from the environment.
  • credentials (Optional[Credentials]) – The OAuth2 Credentials to use for this client. If not passed, falls back to the default inferred from the environment.
  • database (Optional[str]) – The database name that the client targets. For now, DEFAULT_DATABASE (the default value) is the only valid database.
batch()

Get a batch instance from this client.

Returns:A “write” batch to be used for accumulating document changes and sending the changes all at once.
Return type:WriteBatch
collection(*collection_path)

Get a reference to a collection.

For a top-level collection:

>>> client.collection('top')

For a sub-collection:

>>> client.collection('mydocs/doc/subcol')
>>> # is the same as
>>> client.collection('mydocs', 'doc', 'subcol')

Sub-collections can be nested deeper in a similar fashion.

Parameters:collection_path (Tuple[str, ..]) –

Can either be

  • A single /-delimited path to a collection
  • A tuple of collection path segments
Returns:A reference to a collection in the Firestore database.
Return type:CollectionReference
document(*document_path)

Get a reference to a document in a collection.

For a top-level document:

>>> client.document('collek/shun')
>>> # is the same as
>>> client.document('collek', 'shun')

For a document in a sub-collection:

>>> client.document('mydocs/doc/subcol/child')
>>> # is the same as
>>> client.document('mydocs', 'doc', 'subcol', 'child')

Documents in sub-collections can be nested deeper in a similar fashion.

Parameters:document_path (Tuple[str, ..]) –

Can either be

  • A single /-delimited path to a document
  • A tuple of document path segments
Returns:A reference to a document in a collection.
Return type:DocumentReference
static field_path(*field_names)

Create a field path from a list of nested field names.

A field path is a .-delimited concatenation of the field names. It is used to represent a nested field. For example, in the data

data = {
   'aa': {
       'bb': {
           'cc': 10,
       },
   },
}

the field path 'aa.bb.cc' represents the data stored in data['aa']['bb']['cc'].

Parameters:field_names (Tuple[str, ..]) – The list of field names.
Returns:The .-delimited field path.
Return type:str
get_all(references, field_paths=None, transaction=None)

Retrieve a batch of documents.

See field_path() for more information on field paths.

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:
  • references (List[DocumentReference, ..]) – Iterable of document references to be retrieved.
  • field_paths (Optional[Iterable[str, ..]]) – An iterable of field paths (.-delimited list of field names) to use as a projection of document fields in the returned results. If no value is provided, all fields will be returned.
  • transaction (Optional[ Transaction]) – An existing transaction that these references will be retrieved in.
Yields:

.DocumentSnapshot – The next document snapshot that fulfills the query, or None if the document does not exist.

transaction(**kwargs)

Get a transaction that uses this client.

See Transaction for more information on transactions and the constructor arguments.

Parameters:kwargs (Dict[str, Any]) – The keyword arguments (other than client) to pass along to the Transaction constructor.
Returns:A transaction attached to this client.
Return type:Transaction
static write_option(**kwargs)

Create a write option for write operations.

Write operations include set(), update() and delete().

Exactly one of three keyword arguments must be provided:

  • create_if_missing (bool): Indicates if the document should be created if it doesn’t already exist.
  • last_update_time (google.protobuf.timestamp_pb2.           Timestamp): A timestamp. When set, the target document must exist
    and have been last updated at that time. Protobuf update_time timestamps are typically returned from methods that perform write operations as part of a “write result” protobuf or directly.
  • exists (bool): Indicates if the document being modified should already exist.

Providing no argument would make the option have no effect (so it is not allowed). Providing multiple would be an apparent contradiction, since last_update_time assumes that the document was updated (it can’t have been updated if it doesn’t exist) and both create_if_missing and exists indicate that it is unknown if the document exists or not (but in different ways).

Parameters:kwargs (Dict[str, Any]) – The keyword arguments described above.
Raises:TypeError – If anything other than exactly one argument is provided by the caller.
SCOPE = ('https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/datastore')
class google.cloud.firestore.CollectionReference(*path, **kwargs)

Bases: object

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, document_id=None)

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).
Returns:

Pair of

  • The update_time when the document was created (or overwritten).
  • A document reference for the created document.

Return type:

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

Raises:

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

document(document_id=None)

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)

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]) – Either a document snapshot or a dictionary 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)

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]) – Either a document snapshot or a dictionary 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
get(transaction=None)

Read the documents in this collection.

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

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.
Yields:~google.cloud.firestore.document.DocumentSnapshot – The next document that fulfills the query.
limit(count)

Create a limited query with this collection as parent.

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
offset(num_to_skip)

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, **kwargs)

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

select(field_paths)

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)

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]) – Either a document snapshot or a dictionary 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)

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]) – Either a document snapshot or a dictionary 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
where(field_path, op_string, value)

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

Return type:

Query

id

The collection identifier.

Returns:The last component of the path.
Return type:str
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]
class google.cloud.firestore.CreateIfMissingOption(create_if_missing)

Bases: google.cloud.firestore.client.WriteOption

Option used to assert “create if missing” on a write operation.

This will typically be created by write_option().

Parameters:create_if_missing (bool) – Indicates if the document should be created if it doesn’t already exist.
modify_write(write_pb, no_create_msg=None)

Modify a Write protobuf based on the state of this write option.

If:

  • create_if_missing=False, adds a precondition that requires existence
  • create_if_missing=True, does not add any precondition
  • no_create_msg is passed, raises an exception. For example, in a delete(), no “create” can occur, so it wouldn’t make sense to “create if missing”.
Parameters:
  • write_pb (google.cloud.proto.firestore.v1beta1.write_pb2.Write) – A Write protobuf instance to be modified with a precondition determined by the state of this option.
  • no_create_msg (Optional[str]) – A message to use to indicate that a create operation is not allowed.
Raises:

ValueError – If no_create_msg is passed.

class google.cloud.firestore.DocumentReference(*path, **kwargs)

Bases: object

A reference to a document in a Firestore database.

The document may already exist or can be created by this class.

Parameters:
  • path (Tuple[str, ..]) – The components in the document 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 (as well as the base document).
  • kwargs (dict) – The keyword arguments for the constructor. The only supported keyword is client and it must be a Client. It represents the client that created this document 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.
collection(collection_id)

Create a sub-collection underneath the current document.

Parameters:collection_id (str) – The sub-collection identifier (sometimes referred to as the “kind”).
Returns:The child collection.
Return type:CollectionReference
create(document_data)

Create the current document in the Firestore database.

Parameters:document_data (dict) – Property names and values to use for creating a document.
Returns:The write result corresponding to the committed document. A write result contains an update_time field.
Return type:google.cloud.proto.firestore.v1beta1.write_pb2.WriteResult
Raises:Conflict – If the document already exists.
delete(option=None)

Delete the current document in the Firestore database.

Parameters:option (Optional[WriteOption]) – A write option to make assertions / preconditions on the server state of the document before applying changes. Note that create_if_missing can’t be used here since it does not apply (i.e. a “delete” cannot “create”).
Returns:The time that the delete request was received by the server. If the document did not exist when the delete was sent (i.e. nothing was deleted), this method will still succeed and will still return the time that the request was received by the server.
Return type:google.protobuf.timestamp_pb2.Timestamp
Raises:ValueError – If the create_if_missing write option is used.
get(field_paths=None, transaction=None)

Retrieve a snapshot of the current document.

See field_path() for more information on field paths.

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:
  • field_paths (Optional[Iterable[str, ..]]) – An iterable of field paths (.-delimited list of field names) to use as a projection of document fields in the returned results. If no value is provided, all fields will be returned.
  • transaction (Optional[ Transaction]) – An existing transaction that this reference will be retrieved in.
Returns:

A snapshot of the current document.

Return type:

DocumentSnapshot

Raises:

NotFound – If the document does not exist.

set(document_data, option=None)

Replace the current document in the Firestore database.

A write option can be specified to indicate preconditions of the “set” operation. If no option is specified and this document doesn’t exist yet, this method will create it.

Overwrites all content for the document with the fields in document_data. This method performs almost the same functionality as create(). The only difference is that this method doesn’t make any requirements on the existence of the document (unless option is used), whereas as create() will fail if the document already exists.

Parameters:
  • document_data (dict) – Property names and values to use for replacing a document.
  • option (Optional[WriteOption]) – A write option to make assertions / preconditions on the server state of the document before applying changes.
Returns:

The write result corresponding to the committed document. A write result contains an update_time field.

Return type:

google.cloud.proto.firestore.v1beta1.write_pb2.WriteResult

update(field_updates, option=None)

Update an existing document in the Firestore database.

By default, this method verifies that the document exists on the server before making updates. A write option can be specified to override these preconditions.

Each key in field_updates can either be a field name or a field path (For more information on field paths, see field_path().) To illustrate this, consider a document with

>>> snapshot = document.get()
>>> snapshot.to_dict()
{
    'foo': {
        'bar': 'baz',
    },
    'other': True,
}

stored on the server. If the field name is used in the update:

>>> field_updates = {
...     'foo': {
...         'quux': 800,
...     },
... }
>>> document.update(field_updates)

then all of foo will be overwritten on the server and the new value will be

>>> snapshot = document.get()
>>> snapshot.to_dict()
{
    'foo': {
        'quux': 800,
    },
    'other': True,
}

On the other hand, if a .-delimited field path is used in the update:

>>> field_updates = {
...     'foo.quux': 800,
... }
>>> document.update(field_updates)

then only foo.quux will be updated on the server and the field foo.bar will remain intact:

>>> snapshot = document.get()
>>> snapshot.to_dict()
{
    'foo': {
        'bar': 'baz',
        'quux': 800,
    },
    'other': True,
}

To delete / remove a field from an existing document, use the DELETE_FIELD sentinel. So with the example above, sending

>>> field_updates = {
...     'other': firestore.DELETE_FIELD,
... }
>>> document.update(field_updates)

would update the value on the server to:

>>> snapshot = document.get()
>>> snapshot.to_dict()
{
    'foo': {
        'bar': 'baz',
    },
}

To set a field to the current time on the server when the update is received, use the SERVER_TIMESTAMP sentinel. Sending

>>> field_updates = {
...     'foo.now': firestore.SERVER_TIMESTAMP,
... }
>>> document.update(field_updates)

would update the value on the server to:

>>> snapshot = document.get()
>>> snapshot.to_dict()
{
    'foo': {
        'bar': 'baz',
        'now': datetime.datetime(2012, ...),
    },
    'other': True,
}
Parameters:
  • field_updates (dict) – Field names or paths to update and values to update with.
  • option (Optional[WriteOption]) – A write option to make assertions / preconditions on the server state of the document before applying changes.
Returns:

The write result corresponding to the updated document. A write result contains an update_time field.

Return type:

google.cloud.proto.firestore.v1beta1.write_pb2.WriteResult

Raises:

NotFound – If the document does not exist.

id

The document identifier (within its collection).

Returns:The last component of the path.
Return type:str
parent

Collection that owns the current document.

Returns:The parent collection.
Return type:CollectionReference
class google.cloud.firestore.DocumentSnapshot(reference, data, exists, read_time, create_time, update_time)

Bases: object

A snapshot of document data in a Firestore database.

This represents data retrieved at a specific time and may not contain all fields stored for the document (i.e. a hand-picked selection of fields may have been retrieved).

Instances of this class are not intended to be constructed by hand, rather they’ll be returned as responses to various methods, such as get().

Parameters:
  • reference (DocumentReference) – A document reference corresponding to the document that contains the data in this snapshot.
  • data (Dict[str, Any]) – The data retrieved in the snapshot.
  • exists (bool) – Indicates if the document existed at the time the snapshot was retrieved.
  • read_time (google.protobuf.timestamp_pb2.Timestamp) – The time that this snapshot was read from the server.
  • create_time (google.protobuf.timestamp_pb2.Timestamp) – The time that this document was created.
  • update_time (google.protobuf.timestamp_pb2.Timestamp) – The time that this document was last updated.
get(field_path)

Get a value from the snapshot data.

If the data is nested, for example:

>>> snapshot.to_dict()
{
    'top1': {
        'middle2': {
            'bottom3': 20,
            'bottom4': 22,
        },
        'middle5': True,
    },
    'top6': b' foo',
}

a field path can be used to access the nested data. For example:

>>> snapshot.get('top1')
{
    'middle2': {
        'bottom3': 20,
        'bottom4': 22,
    },
    'middle5': True,
}
>>> snapshot.get('top1.middle2')
{
    'bottom3': 20,
    'bottom4': 22,
}
>>> snapshot.get('top1.middle2.bottom3')
20

See field_path() for more information on field paths.

A copy is returned since the data may contain mutable values, but the data stored in the snapshot must remain immutable.

Parameters:field_path (str) – A field path (.-delimited list of field names).
Returns:(A copy of) the value stored for the field_path.
Return type:Any
Raises:KeyError – If the field_path does not match nested data in the snapshot.
to_dict()

Retrieve the data contained in this snapshot.

A copy is returned since the data may contain mutable values, but the data stored in the snapshot must remain immutable.

Returns:The data in the snapshot.
Return type:Dict[str, Any]
exists

Existence flag.

Indicates if the document existed at the time this snapshot was retrieved.

Returns:The existence flag.
Return type:bool
id

The document identifier (within its collection).

Returns:The last component of the path of the document.
Return type:str
reference

Document reference corresponding to document that owns this data.

Returns:A document reference corresponding to this document.
Return type:DocumentReference
class google.cloud.firestore.ExistsOption(exists)

Bases: google.cloud.firestore.client.WriteOption

Option used to assert existence on a write operation.

This will typically be created by write_option().

This option is closely related to CreateIfMissingOption(), but a “create if missing”. In fact,

>>> ExistsOption(exists=True)

is (mostly) equivalent to

>>> CreateIfMissingOption(create_if_missing=False)

The only difference being that “create if missing” cannot be used on some operations (e.g. delete()) while “exists” can.

Parameters:exists (bool) – Indicates if the document being modified should already exist.
modify_write(write_pb, **unused_kwargs)

Modify a Write protobuf based on the state of this write option.

If:

  • exists=True, adds a precondition that requires existence
  • exists=False, adds a precondition that requires non-existence
Parameters:
  • write_pb (google.cloud.proto.firestore.v1beta1.write_pb2.Write) – A Write protobuf instance to be modified with a precondition determined by the state of this option.
  • unused_kwargs (Dict[str, Any]) – Keyword arguments accepted by other subclasses that are unused here.
class google.cloud.firestore.GeoPoint(latitude, longitude)

Bases: object

Simple container for a geo point value.

Parameters:
  • latitude (float) – Latitude of a point.
  • longitude (float) – Longitude of a point.
to_protobuf()

Convert the current object to protobuf.

Returns:The current point as a protobuf.
Return type:google.type.latlng_pb2.LatLng
class google.cloud.firestore.LastUpdateOption(last_update_time)

Bases: google.cloud.firestore.client.WriteOption

Option used to assert a “last update” condition on a write operation.

This will typically be created by write_option().

Parameters:last_update_time (google.protobuf.timestamp_pb2.Timestamp) – A timestamp. When set, the target document must exist and have been last updated at that time. Protobuf update_time timestamps are typically returned from methods that perform write operations as part of a “write result” protobuf or directly.
modify_write(write_pb, **unused_kwargs)

Modify a Write protobuf based on the state of this write option.

The last_update_time is added to write_pb as an “update time” precondition. When set, the target document must exist and have been last updated at that time.

Parameters:
  • write_pb (google.cloud.proto.firestore.v1beta1.write_pb2.Write) – A Write protobuf instance to be modified with a precondition determined by the state of this option.
  • unused_kwargs (Dict[str, Any]) – Keyword arguments accepted by other subclasses that are unused here.
class google.cloud.firestore.Query(parent, projection=None, field_filters=(), orders=(), limit=None, offset=None, start_at=None, end_at=None)

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 (Collection) – The collection that this query applies to.
  • projection (Optional[google.cloud.proto.firestore.v1beta1. query_pb2.StructuredQuery.Projection]) – A projection of document fields to limit the query results to.
  • field_filters (Optional[Tuple[google.cloud.proto.firestore.v1beta1. query_pb2.StructuredQuery.FieldFilter, ..]]) – The filters to be applied in the query.
  • orders (Optional[Tuple[google.cloud.proto.firestore.v1beta1. 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]]) –

    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]]) –

    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.

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]) – Either a document snapshot or a dictionary 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]) – Either a document snapshot or a dictionary 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)

Read the documents in the collection that match this query.

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

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:~google.cloud.firestore.document.DocumentSnapshot – The next document that fulfills the query.
Raises:ValueError – If the first response in the stream is empty, but then more responses follow.
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
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 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
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]) – Either a document snapshot or a dictionary 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]) – Either a document snapshot or a dictionary 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, 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:

ValueError – If value is a NaN or None and op_string is not ==.

ASCENDING = 'ASCENDING'
DESCENDING = 'DESCENDING'
class google.cloud.firestore.Transaction(client, max_attempts=5, read_only=False)

Bases: google.cloud.firestore.batch.WriteBatch

Accumulate read-and-write operations to be sent in a transaction.

Parameters:
  • client (Client) – The client that created this transaction.
  • max_attempts (Optional[int]) – The maximum number of attempts for the transaction (i.e. allowing retries). Defaults to MAX_ATTEMPTS.
  • read_only (Optional[bool]) – Flag indicating if the transaction should be read-only or should allow writes. Defaults to False.
id

Get the current transaction ID.

Returns:The transaction ID (or None if the current transaction is not in progress).
Return type:Optional[bytes]
in_progress

Determine if this transaction has already begun.

Returns:Indicates if the transaction has started.
Return type:bool
class google.cloud.firestore.WriteBatch(client)

Bases: object

Accumulate write operations to be sent in a batch.

This has the same set of methods for write operations that DocumentReference does, e.g. create().

Parameters:client (Client) – The client that created this batch.
commit()

Commit the changes accumulated in this batch.

Returns:The write results corresponding to the changes committed, returned in the same order as the changes were applied to this batch. A write result contains an update_time field.
Return type:List[google.cloud.proto.firestore.v1beta1. write_pb2.WriteResult, ..]
create(reference, document_data)

Add a “change” to this batch to create a document.

If the document given by reference already exists, then this batch will fail when commit()-ed.

Parameters:
  • reference (DocumentReference) – A document reference to be created in this batch.
  • document_data (dict) – Property names and values to use for creating a document.
delete(reference, option=None)

Add a “change” to delete a document.

See delete() for more information on how option determines how the change is applied.

Parameters:
  • reference (DocumentReference) – A document reference that will be deleted in this batch.
  • option (Optional[WriteOption]) – A write option to make assertions / preconditions on the server state of the document before applying changes.
set(reference, document_data, option=None)

Add a “change” to replace a document.

See set() for more information on how option determines how the change is applied.

Parameters:
  • reference (DocumentReference) – A document reference that will have values set in this batch.
  • document_data (dict) – Property names and values to use for replacing a document.
  • option (Optional[WriteOption]) – A write option to make assertions / preconditions on the server state of the document before applying changes.
update(reference, field_updates, option=None)

Add a “change” to update a document.

See update() for more information on field_updates and option.

Parameters:
  • reference (DocumentReference) – A document reference that will be deleted in this batch.
  • field_updates (dict) – Field names or paths to update and values to update with.
  • option (Optional[WriteOption]) – A write option to make assertions / preconditions on the server state of the document before applying changes.
verify(reference, option=None)

Add a “change” to this batch to verify a document’s existence.

Parameters:
  • reference (DocumentReference) – A document reference to be verified.
  • option (Optional[WriteOption]) – A write option to make assertions / preconditions on the server state of the document.
class google.cloud.firestore.WriteOption

Bases: object

Option used to assert a condition on a write operation.

modify_write(write_pb, no_create_msg=None)

Modify a Write protobuf based on the state of this write option.

This is a virtual method intended to be implemented by subclasses.

Parameters:
  • write_pb (google.cloud.proto.firestore.v1beta1.write_pb2.Write) – A Write protobuf instance to be modified with a precondition determined by the state of this option.
  • no_create_msg (Optional[str]) – A message to use to indicate that a create operation is not allowed.
Raises:

NotImplementedError – Always, this method is virtual.

Functions

google.cloud.firestore.transactional(to_wrap)

Decorate a callable so that it runs in a transaction.

Parameters:to_wrap (Callable[Transaction, Any]) – A callable that should be run (and retried) in a transaction.
Returns:the wrapped callable.
Return type:Callable[Transaction, Any]

Send feedback about...

Need help? Visit our support page.