Documents
Classes for representing documents for the Google Cloud Firestore API.
class google.cloud.firestore_v1.base_document.BaseDocumentReference(*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 aClient
. 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 inpath
is not a string * a document ID inpath
is not a stringTypeError – If a keyword other than
client
is used.
_copy_()
Shallow copy the instance.
We leave the client “as-is” but tuple-unpack the path.
Returns
A copy of the current document.
Return type
.DocumentReference
_deepcopy_(unused_memo)
Deep copy the instance.
This isn’t a true deep copy, wee leave the client “as-is” but tuple-unpack the path.
Returns
A copy of the current document.
Return type
.DocumentReference
_eq_(other)
Equality check against another instance.
Parameters
other (Any) – A value to compare against.
Returns
Indicating if the values are equal.
Return type
Union[bool, NotImplementedType]
_ne_(other)
Inequality check against another instance.
Parameters
other (Any) – A value to compare against.
Returns
Indicating if the values are not equal.
Return type
Union[bool, NotImplementedType]
collection(collection_id: str)
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
property id()
The document identifier (within its collection).
Returns
The last component of the path.
Return type
property parent()
Collection that owns the current document.
Returns
The parent collection.
Return type
property path()
Database-relative for this document.
Returns
The document’s relative path.
Return type
class google.cloud.firestore_v1.base_document.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 (
proto.datetime_helpers.DatetimeWithNanoseconds
) – The time that this snapshot was read from the server.create_time (
proto.datetime_helpers.DatetimeWithNanoseconds
) – The time that this document was created.update_time (
proto.datetime_helpers.DatetimeWithNanoseconds
) – The time that this document was last updated.
property exists()
Existence flag.
Indicates if the document existed at the time this snapshot was retrieved.
Returns
The existence flag.
Return type
get(field_path: str)
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
or None if snapshot document does not exist.Return type
Any or None
Raises
KeyError – If the
field_path
does not match nested data in the snapshot.
property id()
The document identifier (within its collection).
Returns
The last component of the path of the document.
Return type
property reference()
Document reference corresponding to document that owns this data.
Returns
A document reference corresponding to this document.
Return type
DocumentReference
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. Returns None if reference does not exist.
Return type
Dict[str, Any] or None
Classes for representing documents for the Google Cloud Firestore API.
class google.cloud.firestore_v1.document.DocumentReference(*path, **kwargs)
Bases: google.cloud.firestore_v1.base_document.BaseDocumentReference
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 aClient
. 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 inpath
is not a string * a document ID inpath
is not a stringTypeError – If a keyword other than
client
is used.
collections(page_size: Optional[int] = None, retry: google.api_core.retry.Retry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None)
List subcollections of the current document.
Parameters
page_size (Optional[int]]) – The maximum number of collections 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 subcollections of the current document. If the document does not exist at the time of snapshot, the iterator will be empty
Return type
Sequence[
CollectionReference
]
create(document_data: dict, retry: google.api_core.retry.Retry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None)
Create a document in the Firestore database.
>>> document_data = {"a": 1, "b": {"c": "Two"}}
>>> document.get().to_dict() is None # does not exist
True
>>> document.create(document_data)
>>> document.get().to_dict() == document_data # exists
True
Parameters
document_data (dict) – Property names and values to use for creating a document.
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 write result corresponding to the committed document. A write result contains an
update_time
field.Return type
Raises
google.cloud.exceptions.Conflict – If the document already exists.
delete(option: Optional[google.cloud.firestore_v1._helpers.WriteOption] = None, retry: google.api_core.retry.Retry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = 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.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 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
get(field_paths: Optional[Iterable[str]] = None, transaction=None, retry: google.api_core.retry.Retry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = 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.retry (google.api_core.retry.Retry) – Designation of what errors, if an y, should be retried. Defaults to a system-specified policy.
timeout (float) – The timeout for this request. Defaults to a system-specified value.
Returns
A snapshot of the current document. If the document does not exist at the time of the snapshot is taken, the snapshot’s
reference
,data
,update_time
, andcreate_time
attributes will all beNone
and itsexists
attribute will beFalse
.Return type
DocumentSnapshot
on_snapshot(callback: Callable)
Watch this document.
This starts a watch on this document using a background thread. The provided callback is run on the snapshot.
Parameters
callback (Callable[[
DocumentSnapshot
], 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(document_snapshot, changes, read_time):
doc = document_snapshot
print(u'{} => {}'.format(doc.id, doc.to_dict()))
doc_ref = db.collection(u'users').document(
u'alovelace' + unique_resource_id())
# Watch this document
doc_watch = doc_ref.on_snapshot(on_snapshot)
# Terminate this watch
doc_watch.unsubscribe()
set(document_data: dict, merge: bool = False, retry: google.api_core.retry.Retry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None)
Create / replace / merge a document in the Firestore database.
- To “upsert” a document (create if it doesn’t exist, replace completely
if it does), leave the
merge
argument at its default:
>>> document_data = {"a": 1, "b": {"c": "Two"}}
>>> document.get().to_dict() is None # document exists
False
>>> document.set(document_data)
>>> document.get().to_dict() == document_data # exists
True
- To “merge”
document_data
with an existing document (creating if the document does not exist), passmerge
as True``:
>>> document_data = {"a": 1, "b": {"c": "Two"}}
>>> document.get().to_dict() == {"d": "Three", "b": {}} # exists
>>> document.set(document_data, merge=True)
>>> document.get().to_dict() == {"a": 1, "d": "Three", "b": {"c": "Two"}}
True
In this case, existing documents with top-level keys which are
not present in document_data
("d"
) will preserve the values
of those keys.
- To merge only specific fields of
document_data
with existing documents (creating if the document does not exist), passmerge
as a list of field paths:
>>> document_data = {"a": 1, "b": {"c": "Two"}}
>>> document.get().to_dict() == {"b": {"c": "One", "d": "Four" }} # exists
True
>>> document.set(document_data, merge=["b.c"])
>>> document.get().to_dict() == {"b": {"c": "Two", "d": "Four" }}
True
For more information on field paths, see
field_path()
.
Parameters
document_data (dict) – Property names and values to use for replacing a document.
merge (Optional[bool] or **Optional[List]) – If True, apply merging instead of overwriting the state of the document.
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 write result corresponding to the committed document. A write result contains an
update_time
field.Return type
update(field_updates: dict, option: Optional[google.cloud.firestore_v1._helpers.WriteOption] = None, retry: google.api_core.retry.Retry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = 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,
}
WARNING: A field path can only be used as a top-level key in
field_updates
.
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.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 write result corresponding to the updated document. A write result contains an
update_time
field.Return type
Raises
google.cloud.exceptions.NotFound – If the document does not exist.
Classes for representing documents for the Google Cloud Firestore API.
class google.cloud.firestore_v1.async_document.AsyncDocumentReference(*path, **kwargs)
Bases: google.cloud.firestore_v1.base_document.BaseDocumentReference
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 aClient
. 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 inpath
is not a string * a document ID inpath
is not a stringTypeError – If a keyword other than
client
is used.
async collections(page_size: Optional[int] = None, retry: google.api_core.retry_async.AsyncRetry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None)
List subcollections of the current document.
Parameters
page_size (Optional[int]]) – The maximum number of collections 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 subcollections of the current document. If the document does not exist at the time of snapshot, the iterator will be empty
Return type
Sequence[
AsyncCollectionReference
]
async create(document_data: dict, retry: google.api_core.retry_async.AsyncRetry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = None)
Create the current document in the Firestore database.
Parameters
document_data (dict) – Property names and values to use for creating a document.
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 write result corresponding to the committed document. A write result contains an
update_time
field.Return type
Raises
google.cloud.exceptions.Conflict – If the document already exists.
async delete(option: Optional[google.cloud.firestore_v1._helpers.WriteOption] = None, retry: google.api_core.retry_async.AsyncRetry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = 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.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 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
async get(field_paths: Optional[Iterable[str]] = None, transaction=None, retry: google.api_core.retry_async.AsyncRetry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = 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[
AsyncTransaction
]) – An existing transaction that this reference will be retrieved 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.
Returns
A snapshot of the current document. If the document does not exist at the time of the snapshot is taken, the snapshot’s
reference
,data
,update_time
, andcreate_time
attributes will all beNone
and itsexists
attribute will beFalse
.Return type
DocumentSnapshot
async set(document_data: dict, merge: bool = False, retry: google.api_core.retry_async.AsyncRetry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = 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.
merge (Optional[bool] or **Optional[List]) – If True, apply merging instead of overwriting the state of the document.
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 write result corresponding to the committed document. A write result contains an
update_time
field.Return type
async update(field_updates: dict, option: Optional[google.cloud.firestore_v1._helpers.WriteOption] = None, retry: google.api_core.retry_async.AsyncRetry = _MethodDefault._DEFAULT_VALUE, timeout: Optional[float] = 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 = await 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,
... },
... }
>>> await document.update(field_updates)
then all of foo
will be overwritten on the server and the new
value will be
>>> snapshot = await 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,
... }
>>> await document.update(field_updates)
then only foo.quux
will be updated on the server and the
field foo.bar
will remain intact:
>>> snapshot = await document.get()
>>> snapshot.to_dict()
{
'foo': {
'bar': 'baz',
'quux': 800,
},
'other': True,
}
WARNING: A field path can only be used as a top-level key in
field_updates
.
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,
... }
>>> await document.update(field_updates)
would update the value on the server to:
>>> snapshot = await 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,
... }
>>> await document.update(field_updates)
would update the value on the server to:
>>> snapshot = await 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.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 write result corresponding to the updated document. A write result contains an
update_time
field.Return type
Raises
google.cloud.exceptions.NotFound – If the document does not exist.