Cloud Datastore Client - Class DatastoreClient (1.19.0)

Reference documentation and code samples for the Cloud Datastore Client class DatastoreClient.

Google Cloud Datastore is a highly-scalable NoSQL database for your applications. Find more information at the Google Cloud Datastore docs.

Cloud Datastore supports multi-tenant applications through use of data partitions. A partition ID can be supplied when creating an instance of Cloud Datastore, and will be used in all operations executed in that instance.

To enable the Google Cloud Datastore Emulator, set the DATASTORE_EMULATOR_HOST environment variable.

Example:

use Google\Cloud\Datastore\DatastoreClient;

$datastore = new DatastoreClient();
// Multi-tenant applications can supply a namespace ID.
use Google\Cloud\Datastore\DatastoreClient;

$datastore = new DatastoreClient([
    'namespaceId' => 'my-application-namespace'
]);
// Using the Datastore Emulator
use Google\Cloud\Datastore\DatastoreClient;

// Be sure to use the port specified when starting the emulator.
// `8900` is used as an example only.
putenv('DATASTORE_EMULATOR_HOST=localhost:8900');

$datastore = new DatastoreClient();
// Multi-database applications can supply a database ID.
use Google\Cloud\Datastore\DatastoreClient;

$datastore = new DatastoreClient([
    'namespaceId' => 'my-application-namespace',
    'databaseId' => 'my-database'
]);

Methods

__construct

Create a Datastore client.

Parameters
NameDescription
config array

Configuration Options.

↳ apiEndpoint string

A hostname with optional port to use in place of the service's default endpoint.

↳ projectId string

The project ID from the Google Developer's Console.

↳ authCache CacheItemPoolInterface

A cache for storing access tokens. Defaults to a simple in memory implementation.

↳ authCacheOptions array

Cache configuration options.

↳ authHttpHandler callable

A handler used to deliver Psr7 requests specifically for authentication.

↳ credentialsFetcher FetchAuthTokenInterface

A credentials fetcher instance.

↳ httpHandler callable

A handler used to deliver Psr7 requests. Only valid for requests sent over REST.

↳ keyFile array

The contents of the service account credentials .json file retrieved from the Google Developer's Console. Ex: json_decode(file_get_contents($path), true).

↳ keyFilePath string

The full path to your service account credentials .json file retrieved from the Google Developers Console.

↳ requestTimeout float

Seconds to wait before timing out the request. Defaults to 0 with REST and 60 with gRPC.

↳ retries int

Number of retries for a failed request. Defaults to 3.

↳ scopes array

Scopes to be used for the request.

↳ quotaProject string

Specifies a user project to bill for access charges associated with the request.

↳ namespaceId string

Partitions data under a namespace. Useful for Multitenant Projects.

↳ databaseId string

ID of the database to which the entities belong.

↳ returnInt64AsObject bool

If true, 64 bit integers will be returned as a Google\Cloud\Datastore\Google\Cloud\Core\Int64 object for 32 bit platform compatibility. Defaults to false.

key

Create a single Key instance

Example:

$key = $datastore->key('Person', 'Bob');
// To override the internal detection of identifier type, you can specify
// which type to use.

$key = $datastore->key('Robots', '1337', [
    'identifierType' => Key::TYPE_NAME
]);
Parameters
NameDescription
kind string

The kind.

identifier string|int

[optional] The ID or name.

options array

Configuration Options

↳ identifierType string

If omitted, type will be determined internally. In cases where any ambiguity can be expected (i.e. if you want to create keys with name but your values may pass PHP's is_numeric() check), this value may be explicitly set using Key::TYPE_ID or Key::TYPE_NAME.

Returns
TypeDescription
Google\Cloud\Datastore\Key

keys

Create multiple keys with the same configuration.

When inserting multiple entities, creating a set of keys at once can be useful. By defining the Key's kind and any ancestors up front, and allowing Cloud Datastore to allocate IDs, you can be sure that your entity identity and ancestry are correct and that there will be no collisions during the insert operation.

Example:

$keys = $datastore->keys('Person', [
    'number' => 10
]);
// Ancestor paths can be specified
$keys = $datastore->keys('Person', [
    'ancestors' => [
        ['kind' => 'Person', 'name' => 'Grandpa Joe'],
        ['kind' => 'Person', 'name' => 'Dad Mike']
    ],
    'number' => 3
]);
Parameters
NameDescription
kind string

The kind to use in the final path element.

options array

Configuration Options

↳ ancestors array[]

An array of PathElement arrays. Use to create ancestor paths.

↳ number int

The number of keys to generate.

↳ id string|int

The ID for the last pathElement.

↳ name string

The Name for the last pathElement.

Returns
TypeDescription
array<Google\Cloud\Datastore\Key>

entity

Create an entity.

This method does not execute any service requests.

Entities are created with a Datastore Key, or by specifying a Kind. Kinds are only allowed for insert operations. For any other case, you must specify a named key. If a kind is given, an ID will be automatically allocated for the entity upon insert. Additionally, if your entity requires a complex key elementPath, you must create the key separately.

In complex applications you may want to create your own entity types. Google Cloud PHP supports subclassing of Google\Cloud\Datastore\Google\Cloud\Datastore\Entity. If the name of a subclass of Entity is given in the options array, an entity will be created with that class rather than the default class.

Example:

$key = $datastore->key('Person', 'Bob');
$entity = $datastore->entity($key, [
    'firstName' => 'Bob',
    'lastName' => 'Testguy'
]);
// Entity values can be assigned and accessed via the array syntax.
$entity = $datastore->entity($key);

$entity['firstName'] = 'Bob';
$entity['lastName'] = 'Testguy';
// Entity values can also be assigned and accessed via an object syntax.
$entity = $datastore->entity($key);

$entity->firstName = 'Bob';
$entity->lastName = 'Testguy';
// Entities can be created with a Kind only, for inserting into datastore
$entity = $datastore->entity('Person');
// Entities can be custom classes implementing the Datastore entity interface.
use Google\Cloud\Datastore\EntityTrait;
use Google\Cloud\Datastore\EntityInterface;

class PersonEntity implements EntityInterface
{
    use EntityTrait;
}

$person = $datastore->entity('Person', [ 'firstName' => 'Bob'], [
    'className' => PersonEntity::class
]);

echo get_class($person); // `Person`
// Custom entity types may also extend the built-in Entity class.
use Google\Cloud\Datastore\Entity;

class OtherPersonEntity extends Entity
}

$person = $datastore->entity('Person', [ 'firstName' => 'Bob'], [
    'className' => OtherPersonEntity::class
]);

echo get_class($person); // `Person`
// If you wish to exclude certain properties from datastore indexes,
// property names may be supplied in the method $options:

$entity = $datastore->entity('Person', [
    'firstName' => 'Bob',
    'dateOfBirth' => new DateTime('January 31, 1969')
], [
    'excludeFromIndexes' => [
        'dateOfBirth'
    ]
]);
Parameters
NameDescription
key Google\Cloud\Datastore\Key|string|null

[optional] The key used to identify the record, or a string $kind. The key may be null only if the entity will be used as an embedded entity within another entity. Attempting to use keyless entities as root entities will result in error. Defaults to null.

entity array

[optional] The data, provided as an array of keys and values to fill the entity with. Defaults to [].

options array

Configuration Options

↳ className string

If set, the given class will be returned. Value must be the name of a class implementing Google\Cloud\Datastore\Google\Cloud\Datastore\EntityInterface. Defaults to Google\Cloud\Datastore\Google\Cloud\Datastore\Entity.

↳ excludeFromIndexes array

A list of entity keys to exclude from datastore indexes.

Returns
TypeDescription
Google\Cloud\Datastore\EntityInterface

geoPoint

Create a new GeoPoint

Example:

$geoPoint = $datastore->geoPoint(37.4220, -122.0841);
Parameters
NameDescription
latitude float

The latitude

longitude float

The longitude

allowNull bool

[optional] Whether null values are allowed. Defaults to false.

Returns
TypeDescription
Google\Cloud\Datastore\GeoPoint

blob

Create a new Blob

Example:

$blob = $datastore->blob('hello world');
// Blobs can be used to store binary data
$blob = $datastore->blob(file_get_contents(__DIR__ .'/family-photo.jpg'));
Parameter
NameDescription
value string|resource|Psr\Http\Message\StreamInterface

The value to store in a blob.

Returns
TypeDescription
Google\Cloud\Datastore\Blob

int64

Create an Int64 object. This can be used to work with 64 bit integers as a string value while on a 32 bit platform.

Example:

$int64 = $datastore->int64('9223372036854775807');
Parameter
NameDescription
value string
Returns
TypeDescription
Google\Cloud\Core\Int64

cursor

Create a Cursor.

A cursor points to a position within a set of entities. Cloud Datastore uses Cursors for paginating query results.

Example:

$cursor = $datastore->cursor($cursorValue);
Parameter
NameDescription
cursorValue string|int
Returns
TypeDescription
Google\Cloud\Datastore\Cursor

allocateId

Allocates an available ID to a given incomplete key

Key MUST be in an incomplete state (i.e. including a kind but not an ID or name in its final pathElement).

This method will execute a service request.

Example:

$key = $datastore->key('Person');
$keyWithAllocatedId = $datastore->allocateId($key);
Parameters
NameDescription
key Google\Cloud\Datastore\Key

The incomplete key.

options array

[optional] Configuration options.

Returns
TypeDescription
Google\Cloud\Datastore\Key

allocateIds

Allocate available IDs to a set of keys

Keys MUST be in an incomplete state (i.e. including a kind but not an ID or name in their final pathElement).

This method will execute a service request.

Example:

$keys = [
    $datastore->key('Person'),
    $datastore->key('Person')
];

$keysWithAllocatedIds = $datastore->allocateIds($keys);
Parameters
NameDescription
keys array<Google\Cloud\Datastore\Key>

The incomplete keys.

options array

[optional] Configuration options.

Returns
TypeDescription
array<Google\Cloud\Datastore\Key>

transaction

Create a Transaction.

Example:

$transaction = $datastore->transaction();
Parameters
NameDescription
options array

Configuration options.

↳ transactionOptions array

Transaction configuration. See ReadWrite.

↳ databaseId string

ID of the database to which the entities belong.

Returns
TypeDescription
Google\Cloud\Datastore\Transaction

readOnlyTransaction

Create a Read-Only Transaction.

Example:

$transaction = $datastore->readOnlyTransaction();

Example with readTime option:

$transaction = $datastore->readOnlyTransaction(['transactionOptions' => ['readTime' => $time]]);
Parameters
NameDescription
options array

Configuration options.

↳ transactionOptions array

See ReadOnly.

↳ databaseId string

ID of the database to which the entities belong.

Returns
TypeDescription
Google\Cloud\Datastore\ReadOnlyTransaction

insert

Insert an entity

An entity with incomplete keys will be allocated an ID prior to insertion.

Insert by this method is non-transactional. If you need transaction support, use Google\Cloud\Datastore\Google\Cloud\Datastore\Transaction::insert().

Example:

$key = $datastore->key('Person', 'Bob');
$entity = $datastore->entity($key, ['firstName' => 'Bob']);

$datastore->insert($entity);
Parameters
NameDescription
entity Google\Cloud\Datastore\EntityInterface

The entity to be inserted.

options array

[optional] Configuration options.

Returns
TypeDescription
stringThe entity version.

insertBatch

Insert multiple entities

Any entity with incomplete keys will be allocated an ID prior to insertion.

Insert by this method is non-transactional. If you need transaction support, use Google\Cloud\Datastore\Google\Cloud\Datastore\Transaction::insertBatch().

Example:


$entities = [
    $datastore->entity('Person', ['firstName' => 'Bob']),
    $datastore->entity('Person', ['firstName' => 'John'])
];

$datastore->insertBatch($entities);
Parameters
NameDescription
entities array<Google\Cloud\Datastore\EntityInterface>

The entities to be inserted.

options array

[optional] Configuration options.

Returns
TypeDescription
array[Response Body](https://cloud.google.com/datastore/reference/rest/v1/projects/commit#response-body)

update

Update an entity

Please note that updating a record in Cloud Datastore will replace the existing record. Adding, editing or removing a single property is only possible by first retrieving the entire entity in its existing state.

Update by this method is non-transactional. If you need transaction support, use Google\Cloud\Datastore\Google\Cloud\Datastore\Transaction::update().

Example:

$entity['firstName'] = 'John';

$datastore->update($entity);
Parameters
NameDescription
entity Google\Cloud\Datastore\EntityInterface

The entity to be updated.

options array

Configuration Options

↳ allowOverwrite bool

Entities must be updated as an entire resource. Patch operations are not supported. Because entities can be created manually, or obtained by a lookup or query, it is possible to accidentally overwrite an existing record with a new one when manually creating an entity. To provide additional safety, this flag must be set to true in order to update a record when the entity provided was not obtained through a lookup or query. Defaults to false.

Returns
TypeDescription
stringThe entity version.

updateBatch

Update multiple entities

Please note that updating a record in Cloud Datastore will replace the existing record. Adding, editing or removing a single property is only possible by first retrieving the entire entity in its existing state.

Update by this method is non-transactional. If you need transaction support, use Google\Cloud\Datastore\Google\Cloud\Datastore\Transaction::updateBatch().

Example:

$entities[0]['firstName'] = 'Bob';
$entities[1]['firstName'] = 'John';

$datastore->updateBatch($entities);
Parameters
NameDescription
entities array<Google\Cloud\Datastore\EntityInterface>

The entities to be updated.

options array

Configuration Options

↳ allowOverwrite bool

Entities must be updated as an entire resource. Patch operations are not supported. Because entities can be created manually, or obtained by a lookup or query, it is possible to accidentally overwrite an existing record with a new one when manually creating an entity. To provide additional safety, this flag must be set to true in order to update a record when the entity provided was not obtained through a lookup or query. Defaults to false.

Returns
TypeDescription
array[Response Body](https://cloud.google.com/datastore/reference/rest/v1/projects/commit#response-body)

upsert

Upsert an entity

Upsert will create a record if one does not already exist, or overwrite existing record if one already exists.

Please note that upserting a record in Cloud Datastore will replace the existing record, if one exists. Adding, editing or removing a single property is only possible by first retrieving the entire entity in its existing state.

An entity with incomplete keys will be allocated an ID prior to insertion.

Upsert by this method is non-transactional. If you need transaction support, use Google\Cloud\Datastore\Google\Cloud\Datastore\Transaction::upsert().

Example:

$key = $datastore->key('Person', 'Bob');
$entity = $datastore->entity($key, ['firstName' => 'Bob']);

$datastore->upsert($entity);
Parameters
NameDescription
entity Google\Cloud\Datastore\EntityInterface

The entity to be upserted.

options array

[optional] Configuration Options.

Returns
TypeDescription
stringThe entity version.

upsertBatch

Upsert multiple entities

Upsert will create a record if one does not already exist, or overwrite an existing record if one already exists.

Please note that upserting a record in Cloud Datastore will replace the existing record, if one exists. Adding, editing or removing a single property is only possible by first retrieving the entire entity in its existing state.

Any entity with incomplete keys will be allocated an ID prior to insertion.

Upsert by this method is non-transactional. If you need transaction support, use Google\Cloud\Datastore\Google\Cloud\Datastore\Transaction::upsertBatch().

Example:

$keys = [
    $datastore->key('Person', 'Bob'),
    $datastore->key('Person', 'John')
];

$entities = [
    $datastore->entity($keys[0], ['firstName' => 'Bob']),
    $datastore->entity($keys[1], ['firstName' => 'John'])
];

$datastore->upsertBatch($entities);
Parameters
NameDescription
entities array<Google\Cloud\Datastore\EntityInterface>

The entities to be upserted.

options array

[optional] Configuration Options.

Returns
TypeDescription
array[Response Body](https://cloud.google.com/datastore/reference/rest/v1/projects/commit#response-body)

delete

Delete an entity

Deletion by this method is non-transactional. If you need transaction support, use Google\Cloud\Datastore\Google\Cloud\Datastore\Transaction::delete().

Example:

$key = $datastore->key('Person', 'Bob');

$datastore->delete($key);
Parameters
NameDescription
key Google\Cloud\Datastore\Key

The identifier to delete.

options array

Configuration options

↳ baseVersion string

Provides concurrency control. The version of the entity that this mutation is being applied to. If this does not match the current version on the server, the mutation conflicts.

Returns
TypeDescription
stringThe updated entity version number.

deleteBatch

Delete multiple entities

Deletion by this method is non-transactional. If you need transaction support, use Google\Cloud\Datastore\Google\Cloud\Datastore\Transaction::deleteBatch().

Example:

$keys = [
    $datastore->key('Person', 'Bob'),
    $datastore->key('Person', 'John')
];

$datastore->deleteBatch($keys);
Parameters
NameDescription
keys array<Google\Cloud\Datastore\Key>

The identifiers to delete.

options array

Configuration options

↳ baseVersion string

Provides concurrency control. The version of the entity that this mutation is being applied to. If this does not match the current version on the server, the mutation conflicts.

Returns
TypeDescription
array[Response Body](https://cloud.google.com/datastore/reference/rest/v1/projects/commit#response-body)

lookup

Retrieve an entity from the datastore

To lookup an entity inside a transaction, use Google\Cloud\Datastore\Google\Cloud\Datastore\Transaction::lookup().

Example:

$key = $datastore->key('Person', 'Bob');

$entity = $datastore->lookup($key);
if (!is_null($entity)) {
    echo $entity['firstName']; // 'Bob'
}

Example with readTime:

$key = $datastore->key('Person', 'Bob');

$entity = $datastore->lookup($key, ['readTime' => $time]);
if (!is_null($entity)) {
    echo $entity['firstName']; // 'Bob'
}
Parameters
NameDescription
key Google\Cloud\Datastore\Key

The identifier to use to locate a desired entity.

options array

Configuration Options

↳ readConsistency string

See ReadConsistency.

↳ className string

If set, the given class will be returned. Value must be the name of a class implementing Google\Cloud\Datastore\Google\Cloud\Datastore\EntityInterface. Defaults to Google\Cloud\Datastore\Google\Cloud\Datastore\Entity.

↳ databaseId string

ID of the database to which the entities belong.

↳ readTime Timestamp

Reads entities as they were at the given timestamp.

Returns
TypeDescription
Google\Cloud\Datastore\EntityInterface|null

lookupBatch

Get multiple entities

To lookup entities inside a transaction, use Google\Cloud\Datastore\Google\Cloud\Datastore\Transaction::lookupBatch().

Example:

$keys = [
    $datastore->key('Person', 'Bob'),
    $datastore->key('Person', 'John')
];

$entities = $datastore->lookupBatch($keys);

foreach ($entities['found'] as $entity) {
    echo $entity['firstName'] . PHP_EOL;
}

Example with readTime:

$keys = [
    $datastore->key('Person', 'Bob'),
    $datastore->key('Person', 'John')
];

$entities = $datastore->lookupBatch($keys, ['readTime' => $time]);

foreach ($entities['found'] as $entity) {
    echo $entity['firstName'] . PHP_EOL;
}
Parameters
NameDescription
keys array<Google\Cloud\Datastore\Key>

The identifiers to look up.

options array

Configuration Options

↳ readConsistency string

See ReadConsistency.

↳ className string|array

If a string, the given class will be returned. Value must be the name of a class implementing Google\Cloud\Datastore\Google\Cloud\Datastore\EntityInterface. If an array is given, it must be an associative array, where the key is a Kind and the value must implement Google\Cloud\Datastore\Google\Cloud\Datastore\EntityInterface. Defaults to Google\Cloud\Datastore\Google\Cloud\Datastore\Entity.

↳ sort bool

If set to true, results in each set will be sorted to match the order given in $keys. Defaults to false.

↳ databaseId string

ID of the database to which the entities belong.

↳ readTime Timestamp

Reads entities as they were at the given timestamp.

Returns
TypeDescription
arrayReturns an array with keys [`found`, `missing`, and `deferred`]. Members of `found` will be instance of {@see \Google\Cloud\Datastore\Google\Cloud\Datastore\Entity}. Members of `missing` and `deferred` will be instance of {@see \Google\Cloud\Datastore\Google\Cloud\Datastore\Key}.

query

Create a Query object.

The Query class can be used as a builder, or it can accept a query representation at instantiation.

Example:

$query = $datastore->query();
Parameter
NameDescription
query array

Query

Returns
TypeDescription
Google\Cloud\Datastore\Query\Query

gqlQuery

Create a GqlQuery object.

Returns a Query object which can be executed using Google\Cloud\Datastore\Google\Cloud\Datastore\DatastoreClient::runQuery().

Example:

$query = $datastore->gqlQuery('SELECT * FROM Companies');
// Literals must be provided as bound parameters by default:
$query = $datastore->gqlQuery('SELECT * FROM Companies WHERE companyName = @companyName', [
    'bindings' => [
        'companyName' => 'Google'
    ]
]);
// Positional binding is also supported:
$query = $datastore->gqlQuery('SELECT * FROM Companies WHERE companyName = @1 LIMIT 1', [
    'bindings' => [
        'Google'
    ]
]);
// While not recommended, you can use literals in your query string:
$query = $datastore->gqlQuery('SELECT * FROM Companies WHERE companyName = \'Google\'', [
    'allowLiterals' => true
]);
// Using cursors as query bindings:
$cursor = $datastore->cursor($cursorValue);

$query = $datastore->gqlQuery('SELECT * FROM Companies OFFSET @offset', [
    'bindings' => [
        'offset' => $cursor
    ]
]);
Parameters
NameDescription
query string

The GQL Query string.

options array

Configuration Options

↳ allowLiterals bool

Whether literal values will be allowed in the query string. Parameter binding is strongly encouraged over literals. Defaults to false.

↳ bindings array

An array of values to bind to the query string. Queries using Named Bindings should provide a key/value set, while queries using Positional Bindings must provide a simple array. Query cursors may be provided using instances of Google\Cloud\Datastore\Google\Cloud\Datastore\Cursor.

↳ readConsistency string

See ReadConsistency.

Returns
TypeDescription
Google\Cloud\Datastore\Query\GqlQuery

runQuery

Run a query and return entities

To query datastore inside a transaction, use Google\Cloud\Datastore\Google\Cloud\Datastore\Transaction::runQuery().

Example:

$result = $datastore->runQuery($query);

foreach ($result as $entity) {
    echo $entity['firstName'];
}

Example with readTime:

$result = $datastore->runQuery($query, ['readTime' => $time]);

foreach ($result as $entity) {
    echo $entity['firstName'];
}
Parameters
NameDescription
query Google\Cloud\Datastore\Query\QueryInterface

A query object.

options array

Configuration Options

↳ className string

If set, the given class will be returned. Value must be the name of a class implementing Google\Cloud\Datastore\Google\Cloud\Datastore\EntityInterface. Defaults to Google\Cloud\Datastore\Google\Cloud\Datastore\Entity.

↳ readConsistency string

See ReadConsistency.

↳ readTime Timestamp

Reads entities as they were at the given timestamp.

Returns
TypeDescription
Google\Cloud\Datastore\EntityIterator<\google\cloud\datastore\entityinterface>

Constants

VERSION

Value: '1.19.0'

FULL_CONTROL_SCOPE

Value: 'https://www.googleapis.com/auth/datastore'