Package Classes (2.22.0)

Summary of entries of Classes for datastore.

Classes

AggregationQuery

An Aggregation query against the Cloud Datastore.

This class serves as an abstraction for creating aggregations over queryin the Cloud Datastore.

AggregationResult

A class representing result from Aggregation Query

AggregationResultIterator

Represent the state of a given execution of a Query.

AvgAggregation

Representation of a "Avg" aggregation query.

BaseAggregation

Base class representing an Aggregation operation in Datastore

CountAggregation

Representation of a "Count" aggregation query.

SumAggregation

Representation of a "Sum" aggregation query.

Batch

An abstraction representing a collected group of updates / deletes.

Used to build up a bulk mutation.

For example, the following snippet of code will put the twosaveoperations and thedelete operation into the same mutation, and sendthem to the server in a single API request:

.. testsetup:: batch

import uuidfrom google.cloud importdatastoreunique = str(uuid.uuid4())[0:8]client =datastore.Client(namespace='ns{}'.format(unique))

.. doctest:: batch

>>> entity1 = datastore.Entity(client.key('EntityKind', 1234))>>> entity2 = datastore.Entity(client.key('EntityKind', 2345))>>> key3 = client.key('EntityKind', 3456)>>> batch = client.batch()>>> batch.begin()>>> batch.put(entity1)>>> batch.put(entity2)>>> batch.delete(key3)>>> batch.commit()

You can also use a batch as a context manager, in which casecommit will be called automatically if its block exits withoutraising an exception:

.. doctest:: batch

>>> with client.batch() as batch:...     batch.put(entity1)...     batch.put(entity2)...     batch.delete(key3)

By default, no updates will be sent if the block exits with an error:

.. doctest:: batch

>>> def do_some_work(batch):...    return>>> with client.batch() as batch:...     do_some_work(batch)...     raise Exception()  # rolls backTraceback (most recent call last):  ...Exception

.. testcleanup:: txn

with client.batch() as batch:    batch.delete(client.key('EntityKind', 1234))    batch.delete(client.key('EntityKind', 2345))

Client

Convenience wrapper for invoking APIs/factories w/ a project.

.. doctest::

from google.cloud import datastoreclient = datastore.Client()

Entity

Entities are akin to rows in a relational database

An entity storing the actual instance of data.

Each entity is officially represented with axref_Key, however it is possible thatyou might create an entity with only a partial key (that is, a keywith a kind, and possibly a parent, but without an ID). In such acase, the datastore service will automatically assign an ID to thepartial key.

Entities in this API act like dictionaries with extras built in thatallow you to delete or persist the data stored on the entity.

Entities are mutable and act like a subclass of a dictionary.This means you could take an existing entity and change the keyto duplicate the object.

Use xref_get to retrieve anexisting entity:

.. testsetup:: entity-ctor

import uuidfrom google.cloud importdatastoreunique = str(uuid.uuid4())[0:8]client =datastore.Client(namespace='ns{}'.format(unique))entity =datastore.Entity(client.key('EntityKind', 1234))entity['property'] = 'value'client.put(entity)

.. doctest:: entity-ctor

>>> key = client.key('EntityKind', 1234)>>> client.get(key)<Entity('EntityKind', 1234) {'property': 'value'}>

You can the set values on the entity just like you would on anyother dictionary.

.. doctest:: entity-ctor

>>> entity['age'] = 20>>> entity['name'] = 'JJ'

.. testcleanup:: entity-ctor

client.delete(entity.key)

However, not all types are allowed as a value for a Google Cloud Datastoreentity. The following basic types are supported by the API:

  • datetime.datetime
  • xref_Key
  • bool
  • float
  • int (as well aslong in Python 2)
  • unicode (calledstr in Python 3)
  • bytes (calledstr in Python 2)
  • xref_GeoPoint
  • :data:None

In addition, three container types are supported:

  • list
  • xref_Entity
  • dict (will just be treated like anEntity withouta key orexclude_from_indexes)

Each entry in a list must be one of the value types (basic orcontainer) and each value in anxref_Entity must as well. Inthis case an xref_Entityas acontainer acts as adict, but also has the special annotationsofkey andexclude_from_indexes.

And you can treat an entity like a regular Python dictionary:

.. testsetup:: entity-dict

from google.cloud importdatastoreentity =datastore.Entity()entity['age'] = 20entity['name'] = 'JJ'

.. doctest:: entity-dict

>>> sorted(entity.keys())['age', 'name']>>> sorted(entity.items())[('age', 20), ('name', 'JJ')]
Note:When saving an entity to the backend, values which are "text"(unicode in Python2,str in Python3) will be saved usingthe 'text_value' field, after being encoded to UTF-8. Whenretrieved from the back-end, such values will be decoded to "text"again. Values which are "bytes" (str in Python2,bytes inPython3), will be saved using the 'blob_value' field, withoutany decoding / encoding step.

GeoPoint

Simple container for a geo point value.

Key

An immutable representation of a datastore Key.

.. testsetup:: key-ctor

from google.cloud import datastore

project = 'my-special-pony' client = datastore.Client(project=project) Key = datastore.Key

parent_key = client.key('Parent', 'foo')

To create a basic key directly:

.. doctest:: key-ctor

Key('EntityKind', 1234, project=project) <Key('EntityKind', 1234), project=...>Key('EntityKind', 'foo', project=project) <Key('EntityKind', 'foo'), project=...>

Though typical usage comes via thexref_key factory:

.. doctest:: key-ctor

client.key('EntityKind', 1234) <Key('EntityKind', 1234), project=...>client.key('EntityKind', 'foo') <Key('EntityKind', 'foo'), project=...>

To create a key with a parent:

.. doctest:: key-ctor

client.key('Parent', 'foo', 'Child', 1234) <Key('Parent', 'foo', 'Child', 1234), project=...>client.key('Child', 1234, parent=parent_key) <Key('Parent', 'foo', 'Child', 1234), project=...>

To create a partial key:

.. doctest:: key-ctor

client.key('Parent', 'foo', 'Child') <Key('Parent', 'foo', 'Child'), project=...>

To create a key from a non-default database:

.. doctest:: key-ctor

Key('EntityKind', 1234, project=project, database='mydb') <Key('EntityKind', 1234), project=my-special-pony, database=mydb>

And

Class representation of an AND Filter.

BaseCompositeFilter

Base class for a Composite Filter. (either OR or AND).

BaseFilter

Base class for Filters

Iterator

Represent the state of a given execution of a Query.

Or

Class representation of an OR Filter.

PropertyFilter

Class representation of a Property Filter

Query

A Query against the Cloud Datastore.

This class serves as an abstraction for creating a query over datastored in the Cloud Datastore.

Transaction

An abstraction representing datastore Transactions.

Transactions can be used to build up a bulk mutation and ensure allor none succeed (transactionally).

For example, the following snippet of code will put the twosaveoperations (eitherinsert orupsert) into the samemutation, and execute those within a transaction:

.. testsetup:: txn

import uuidfrom google.cloud importdatastoreunique = str(uuid.uuid4())[0:8]client =datastore.Client(namespace='ns{}'.format(unique))

.. doctest:: txn

>>> entity1 = datastore.Entity(client.key('EntityKind', 1234))>>> entity2 = datastore.Entity(client.key('EntityKind', 2345))>>> with client.transaction():...     client.put_multi([entity1, entity2])

Because it derives from xref_Batch,Transaction also providesput anddelete methods:

.. doctest:: txn

with client.transaction() as xact: ... xact.put(entity1) ... xact.delete(entity2.key)

By default, the transaction is rolled back if the transaction blockexits with an error:

.. doctest:: txn

>>> def do_some_work():...    return>>> class SomeException(Exception):...    pass>>> with client.transaction():...     do_some_work()...     raise SomeException  # rolls backTraceback (most recent call last):  ...SomeException

If the transaction block exits without an exception, it will commitby default.

Warning:Inside a transaction, automatically assigned IDs forentities will not be available at save time! That means, if youtry:.. doctest:: txn

with client.transaction(): ... thing1 = datastore.Entity(key=client.key('Thing')) ... client.put(thing1)

Once you exit the transaction (or callcommit), the automatically generated ID will be assigned to the entity:

.. doctest:: txn

  >>> with client.transaction():  ...     thing2 = datastore.Entity(key=client.key('Thing'))  ...     client.put(thing2)  ...     print(thing2.key.is_partial)  # There is no ID on this key.  ...  True  >>> print(thing2.key.is_partial)  # There *is* an ID.  False

If you don't want to use the context manager you can initialize atransaction manually:

.. doctest:: txn

transaction = client.transaction()transaction.begin()

thing3 = datastore.Entity(key=client.key('Thing'))transaction.put(thing3)

transaction.commit()

.. testcleanup:: txn

with client.batch() as batch:    batch.delete(client.key('EntityKind', 1234))    batch.delete(client.key('EntityKind', 2345))    batch.delete(thing1.key)    batch.delete(thing2.key)    batch.delete(thing3.key)

DatastoreAdminClient

Google Cloud Datastore Admin API

The Datastore Admin API provides several admin services forCloud Datastore.

Concepts: Project, namespace, kind, and entity as defined in theGoogle Cloud Datastore API.

Operation: An Operation represents work being performed in thebackground.

EntityFilter: Allows specifying a subset of entities in aproject. This is specified as a combination of kinds andnamespaces (either or both of which may be all).

Export/Import Service:

  • The Export/Import service provides the ability to copy all ora subset of entities to/from Google Cloud Storage.
  • Exported data may be imported into Cloud Datastore for anyGoogle Cloud Platform project. It is not restricted to theexport source project. It is possible to export from oneproject and then import into another.
  • Exported data can also be loaded into Google BigQuery foranalysis.
  • Exports and imports are performed asynchronously. An Operationresource is created for each export/import. The state(including any errors encountered) of the export/import may bequeried via the Operation resource.

Index Service:

  • The index service manages Cloud Datastore composite indexes.
  • Index creation and deletion are performed asynchronously. AnOperation resource is created for each such asynchronousoperation. The state of the operation (including any errorsencountered) may be queried via the Operation resource.

Operation Service:

  • The Operations collection provides a record of actionsperformed for the specified project (including any operationsin progress). Operations are not created directly but throughcalls on other collections or resources.
  • An operation that is not yet done may be cancelled. Therequest to cancel is asynchronous and the operation maycontinue to run for some time after the request to cancel ismade.
  • An operation that is done may be deleted so that it is nolonger listed as part of the Operation collection.
  • ListOperations returns all pending operations, but notcompleted operations.
  • Operations are created by service DatastoreAdmin, but areaccessed via service google.longrunning.Operations.

Modules

aggregation

API documentation fordatastore.aggregation module.

batch

Create / interact with a batch of updates / deletes.

Batches provide the ability to execute multiple operationsin a single request to the Cloud Datastore API.

Seehttps://cloud.google.com/datastore/docs/concepts/entities#batch_operations

client

Convenience wrapper for invoking APIs/factories w/ a project.

entity

Class for representing a single entity in the Cloud Datastore.

helpers

Helper functions for dealing with Cloud Datastore's Protobuf API.

The non-private functions are part of the API.

key

Create / interact with Google Cloud Datastore keys.

query

Create / interact with Google Cloud Datastore queries.

transaction

Create / interact with Google Cloud Datastore transactions.

client

API documentation fordatastore_admin_v1.services.datastore_admin.client module.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-16 UTC.