Interface Datastore (2.24.3)

publicinterface DatastoreextendsService<DatastoreOptions>,DatastoreReaderWriter

An interface for Google Cloud Datastore.

Implements

com.google.cloud.Service<com.google.cloud.datastore.DatastoreOptions>, DatastoreReaderWriter

Methods

<T>run(Query<T> query, ReadOption[] options)

publicabstractQueryResults<T><T>run(Query<T>query,ReadOption[]options)

Submits a Query and returns its result. ReadOptions can be specified if desired.

Example of running a query to find all entities of one kind.


Stringkind="my_kind";
StructuredQuery<Entity>query=Query.newEntityQueryBuilder()
.setKind(kind)
.build();
QueryResults<Entity>results=datastore.run(query);
List<Entity>entities=Lists.newArrayList();
while(results.hasNext()){
Entityresult=results.next();
// do something with result
entities.add(result);
}

Example of running a query to find all entities with a matching property value.


Stringkind="my_kind";
Stringproperty="my_property";
Stringvalue="my_value";
StructuredQuery<Entity>query=Query.newEntityQueryBuilder()
.setKind(kind)
.setFilter(PropertyFilter.eq(property,value))
.build();
QueryResults<Entity>results=datastore.run(query);
List<Entity>entities=Lists.newArrayList();
while(results.hasNext()){
Entityresult=results.next();
// do something with result
entities.add(result);
}
Parameters
Name Description
query Query<T>
options ReadOption[]
Returns
Type Description
QueryResults<T>

<T>run(Query<T> query, ExplainOptions explainOptions, ReadOption[] options)

publicdefaultQueryResults<T><T>run(Query<T>query,ExplainOptionsexplainOptions,ReadOption[]options)

Submits a Query with specified com.google.cloud.datastore.models.ExplainOptions and returns its result. ReadOptions can be specified if desired.

Example of running a query to find all entities of one kind.


Stringkind="my_kind";
StructuredQuery<Entity>query=Query.newEntityQueryBuilder()
.setKind(kind)
.build();
QueryResults<Entity>results=datastore.run(query,ExplainOptions.newBuilder().setAnalyze(true).build());
Parameters
Name Description
query Query<T>
explainOptions ExplainOptions
options ReadOption[]
Returns
Type Description
QueryResults<T>

<T>runInTransaction(Datastore.TransactionCallable<T> callable)

publicabstractT<T>runInTransaction(Datastore.TransactionCallable<T>callable)

Invokes the callback's Datastore.TransactionCallable#run method with a DatastoreReaderWriter that is associated with a new transaction. The transaction will be committed upon successful invocation. Any thrown exception will cause the transaction to rollback and will be propagated as a DatastoreException with the original exception as its root cause.

Example of running in a transaction.


StringcallableResult="my_callable_result";
TransactionCallable<String>callable=newTransactionCallable<String>(){
publicStringrun(DatastoreReaderWriterreaderWriter){
// use readerWriter to run in transaction
returncallableResult;
}
};
Stringresult=datastore.runInTransaction(callable);
Parameter
Name Description
callable TransactionCallable<T>

the callback to call with a newly created transactional readerWriter

Returns
Type Description
T

<T>runInTransaction(Datastore.TransactionCallable<T> callable, TransactionOptions options)

publicabstractT<T>runInTransaction(Datastore.TransactionCallable<T>callable,TransactionOptionsoptions)

Invokes the callback's Datastore.TransactionCallable#run method with a DatastoreReaderWriter that is associated with a new transaction. The transaction will be committed upon successful invocation. Any thrown exception will cause the transaction to rollback and will be propagated as a DatastoreException with the original exception as its root cause. If TransactionOptions is set to read-write mode, previous transaction Id in the options will be automatically populated each time a transaction is retried.

Example of running in a transaction.


StringcallableResult="my_callable_result";
TransactionCallable<String>callable=newTransactionCallable<String>(){
publicStringrun(DatastoreReaderWriterreaderWriter){
// use readerWriter to run in transaction
returncallableResult;
}
};
TransactionOptionsoptions=TransactionOptions.newBuilder()
.setReadWrite(TransactionOptions.ReadWrite
.getDefaultInstance())
.build();
Stringresult=datastore.runInTransaction(callable,options);
Parameters
Name Description
callable TransactionCallable<T>

the callback to call with a newly created transactional readerWriter

options TransactionOptions

the Transaction options indicating whether the transaction mode is Read-only or Read-Write

Returns
Type Description
T

add(FullEntity<?> entity)

publicabstractEntityadd(FullEntity<?>entity)

Datastore add operation: inserts the provided entity. This method will automatically allocate an id if necessary.

If an entity for entity.getKey() does not exist, entity is inserted. Otherwise, a DatastoreException is thrown with DatastoreException#getReason() equal to "ALREADY_EXISTS".

Example of adding a single entity.


StringkeyName="my_key_name";
Keykey=datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
Entity.BuilderentityBuilder=Entity.newBuilder(key);
entityBuilder.set("propertyName","value");
Entityentity=entityBuilder.build();
try{
datastore.add(entity);
}catch(DatastoreExceptionex){
if("ALREADY_EXISTS".equals(ex.getReason())){
// entity.getKey() already exists
}
}
Parameter
Name Description
entity FullEntity<?>
Returns
Type Description
Entity

add(FullEntity<?>[] entities)

publicabstractList<Entity>add(FullEntity<?>[]entities)

Datastore add operation: inserts the provided entities. This method will automatically allocate id for any entity with an incomplete key.

If none of entities' keys exist, all entities are inserted. If any of entities' keys already exists the method throws a DatastoreException with DatastoreException#getReason() equal to "ALREADY_EXISTS". All entities in entities whose key did not exist are inserted. To achieve a transactional behavior, use Transaction.

Example of adding multiple entities.


StringkeyName1="my_key_name1";
StringkeyName2="my_key_name2";
Keykey1=datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
Entity.BuilderentityBuilder1=Entity.newBuilder(key1);
entityBuilder1.set("propertyName","value1");
Entityentity1=entityBuilder1.build();
Keykey2=datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
Entity.BuilderentityBuilder2=Entity.newBuilder(key2);
entityBuilder2.set("propertyName","value2");
Entityentity2=entityBuilder2.build();
try{
datastore.add(entity1,entity2);
}catch(DatastoreExceptionex){
if("ALREADY_EXISTS".equals(ex.getReason())){
// at least one of entity1.getKey() and entity2.getKey() already exists
}
}
Parameter
Name Description
entities FullEntity<?>[]
Returns
Type Description
List<Entity>

allocateId(IncompleteKey key)

publicabstractKeyallocateId(IncompleteKeykey)

Allocate a unique id for the given key. The returned key will have the same information (projectId, kind, namespace and ancestors) as the given key and will have a newly assigned id.

Example of allocating an id.


KeyFactorykeyFactory=datastore.newKeyFactory().setKind("MyKind");
IncompleteKeyincompleteKey=keyFactory.newKey();
// let cloud datastore automatically assign an id
Keykey=datastore.allocateId(incompleteKey);
Parameter
Name Description
key IncompleteKey
Returns
Type Description
Key

allocateId(IncompleteKey[] keys)

publicabstractList<Key>allocateId(IncompleteKey[]keys)

Returns a list of keys using the allocated ids ordered by the input.

Example of allocating multiple ids in a single batch.


KeyFactorykeyFactory=datastore.newKeyFactory().setKind("MyKind");
IncompleteKeyincompleteKey1=keyFactory.newKey();
IncompleteKeyincompleteKey2=keyFactory.newKey();
// let cloud datastore automatically assign the ids
List<Key>keys=datastore.allocateId(incompleteKey1,incompleteKey2);

See Also: #allocateId(IncompleteKey)

Parameter
Name Description
keys IncompleteKey[]
Returns
Type Description
List<Key>

delete(Key[] keys)

publicabstractvoiddelete(Key[]keys)

A datastore delete operation. It is OK to request the deletion of a non-existing key.

Example of deleting multiple entities.


StringkeyName1="my_key_name1";
StringkeyName2="my_key_name2";
Keykey1=datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
Keykey2=datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
datastore.delete(key1,key2);
Parameter
Name Description
keys Key[]

fetch(Iterable<Key> keys, ReadOption[] options)

publicabstractList<Entity>fetch(Iterable<Key>keys,ReadOption[]options)

Returns a list with a value for each given key (ordered by input). null values are returned for nonexistent keys. When possible prefer using #get(Key...) to avoid eagerly loading the results. ReadOptions can be specified if desired.

Example of fetching a list of Entity objects.


StringfirstKeyName="my_first_key_name";
StringsecondKeyName="my_second_key_name";
KeyFactorykeyFactory=datastore.newKeyFactory().setKind("MyKind");
KeyfirstKey=keyFactory.newKey(firstKeyName);
KeysecondKey=keyFactory.newKey(secondKeyName);
List<Entity>entities=datastore.fetch(Lists.newArrayList(firstKey,secondKey));
for(Entityentity:entities){
// do something with the entity
}
Parameters
Name Description
keys Iterable<Key>
options ReadOption[]
Returns
Type Description
List<Entity>

get(Key key, ReadOption[] options)

publicabstractEntityget(Keykey,ReadOption[]options)

Returns an Entity for the given Key or null if it doesn't exist. ReadOptions can be specified if desired.

Example of getting an entity.


StringkeyName="my_key_name";
Keykey=datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
Entityentity=datastore.get(key);
// Do something with the entity
Parameters
Name Description
key Key
options ReadOption[]
Returns
Type Description
Entity

get(Iterable<Key> keys, ReadOption[] options)

publicabstractIterator<Entity>get(Iterable<Key>keys,ReadOption[]options)

Returns an Entity for each given Key that exists in the Datastore. The order of the result is unspecified. Results are loaded lazily, so it is possible to get a DatastoreException from the returned Iterator's hasNext or next methods. ReadOptions can be specified if desired.

Example of getting multiple entity objects.


StringfirstKeyName="my_first_key_name";
StringsecondKeyName="my_second_key_name";
KeyFactorykeyFactory=datastore.newKeyFactory().setKind("MyKind");
KeyfirstKey=keyFactory.newKey(firstKeyName);
KeysecondKey=keyFactory.newKey(secondKeyName);
Iterator<Entity>entitiesIterator=datastore.get(Lists.newArrayList(firstKey,secondKey));
List<Entity>entities=Lists.newArrayList();
while(entitiesIterator.hasNext()){
Entityentity=entitiesIterator.next();
// do something with the entity
entities.add(entity);
}

See Also: #get(Key)

Parameters
Name Description
keys Iterable<Key>
options ReadOption[]
Returns
Type Description
Iterator<Entity>

newBatch()

publicabstractBatchnewBatch()

Returns a new Batch for processing multiple write operations in one request.

Example of starting a new batch.


StringkeyName1="my_key_name_1";
StringkeyName2="my_key_name_2";
Keykey1=datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
Keykey2=datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
Batchbatch=datastore.newBatch();
Entityentity1=Entity.newBuilder(key1).set("name","John").build();
Entityentity2=Entity.newBuilder(key2).set("title","title").build();
batch.add(entity1);
batch.add(entity2);
batch.submit();
Returns
Type Description
Batch

newKeyFactory()

publicabstractKeyFactorynewKeyFactory()

Returns a new KeyFactory for this service

Example of creating a KeyFactory.


KeyFactorykeyFactory=datastore.newKeyFactory();
Returns
Type Description
KeyFactory

newTransaction()

publicabstractTransactionnewTransaction()

Returns a new Datastore transaction.

Returns
Type Description
Transaction

newTransaction(TransactionOptions options)

publicabstractTransactionnewTransaction(TransactionOptionsoptions)

Returns a new Datastore transaction.

Parameter
Name Description
options TransactionOptions

a transaction option indicating the mode of the transaction (read-only or read-write)

Returns
Type Description
Transaction

put(FullEntity<?> entity)

publicabstractEntityput(FullEntity<?>entity)

A Datastore put (a.k.a upsert) operation: inserts an entity if it does not exist, updates it otherwise. This method will automatically allocate an id if necessary.

Example of putting a single entity.


StringkeyName="my_key_name";
Keykey=datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
Entity.BuilderentityBuilder=Entity.newBuilder(key);
entityBuilder.set("propertyName","value");
Entityentity=entityBuilder.build();
datastore.put(entity);
Parameter
Name Description
entity FullEntity<?>
Returns
Type Description
Entity

put(FullEntity<?>[] entities)

publicabstractList<Entity>put(FullEntity<?>[]entities)

A Datastore put (a.k.a upsert) operation: creates an entity if it does not exist, updates it otherwise. This method will automatically allocate id for any entity with an incomplete key.

Example of putting multiple entities.


StringkeyName1="my_key_name1";
StringkeyName2="my_key_name2";
Keykey1=datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
Entity.BuilderentityBuilder1=Entity.newBuilder(key1);
entityBuilder1.set("propertyName","value1");
Entityentity1=entityBuilder1.build();
Keykey2=datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
Entity.BuilderentityBuilder2=Entity.newBuilder(key2);
entityBuilder2.set("propertyName","value2");
Entityentity2=entityBuilder2.build();
datastore.put(entity1,entity2);
Parameter
Name Description
entities FullEntity<?>[]
Returns
Type Description
List<Entity>

reserveIds(Key[] keys)

publicabstractList<Key>reserveIds(Key[]keys)

Reserve one or more keys, preventing them from being automatically allocated by Datastore.

Example of reserving multiple ids in a single batch.


KeyFactorykeyFactory=datastore.newKeyFactory().setKind("MyKind");
Keykey1=keyFactory.newKey(10);
Keykey2=keyFactory.newKey("name");
List<Key>keys=datastore.reserveIds(key1,key2);
Parameter
Name Description
keys Key[]
Returns
Type Description
List<Key>

runAggregation(AggregationQuery query, ReadOption[] options)

publicdefaultAggregationResultsrunAggregation(AggregationQueryquery,ReadOption[]options)

Submits a AggregationQuery and returns AggregationResults. ReadOptions can be specified if desired.

Example of running an AggregationQuery to find the count of entities of one kind.

StructuredQuery example:


EntityQueryselectAllQuery=Query.newEntityQueryBuilder()
.setKind("Task")
.build();
AggregationQueryaggregationQuery=Query.newAggregationQueryBuilder()
.addAggregation(count().as("total_count"))
.over(selectAllQuery)
.build();
AggregationResultsaggregationResults=datastore.runAggregation(aggregationQuery);
for(AggregationResultaggregationResult:aggregationResults){
System.out.println(aggregationResult.get("total_count"));
}

GqlQuery example:


GqlQueryselectAllGqlQuery=Query.newGqlQueryBuilder(
"AGGREGATE COUNT(*) AS total_count, COUNT_UP_TO(100) AS count_upto_100 OVER(SELECT * FROM Task)"
)
.setAllowLiteral(true)
.build();
AggregationQueryaggregationQuery=Query.newAggregationQueryBuilder()
.over(selectAllGqlQuery)
.build();
AggregationResultsaggregationResults=datastore.runAggregation(aggregationQuery);
for(AggregationResultaggregationResult:aggregationResults){
System.out.println(aggregationResult.get("total_count"));
System.out.println(aggregationResult.get("count_upto_100"));
}
Parameters
Name Description
query AggregationQuery
options ReadOption[]
Returns
Type Description
AggregationResults AggregationResults

runAggregation(AggregationQuery query, ExplainOptions explainOptions, ReadOption[] options)

publicdefaultAggregationResultsrunAggregation(AggregationQueryquery,ExplainOptionsexplainOptions,ReadOption[]options)

Submits a AggregationQuery with specified com.google.cloud.datastore.models.ExplainOptions and returns AggregationResults. ReadOptions can be specified if desired.

Example of running an AggregationQuery to find the count of entities of one kind.

StructuredQuery example:


EntityQueryselectAllQuery=Query.newEntityQueryBuilder()
.setKind("Task")
.build();
AggregationQueryaggregationQuery=Query.newAggregationQueryBuilder()
.addAggregation(count().as("total_count"))
.over(selectAllQuery)
.build();
AggregationResultsaggregationResults=datastore.runAggregation(aggregationQuery,ExplainOptions.newBuilder().setAnalyze(true).build());
Parameters
Name Description
query AggregationQuery
explainOptions ExplainOptions
options ReadOption[]
Returns
Type Description
AggregationResults AggregationResults

update(Entity[] entities)

publicabstractvoidupdate(Entity[]entities)

A Datastore update operation. The operation will fail if an entity with the same key does not already exist.

Example of updating multiple entities.


StringkeyName1="my_key_name_1";
StringkeyName2="my_key_name_2";
Keykey1=datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
Entity.BuilderentityBuilder1=Entity.newBuilder(key1);
entityBuilder1.set("propertyName","updatedValue1");
Entityentity1=entityBuilder1.build();
Keykey2=datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
Entity.BuilderentityBuilder2=Entity.newBuilder(key2);
entityBuilder2.set("propertyName","updatedValue2");
Entityentity2=entityBuilder2.build();
datastore.update(entity1,entity2);
Parameter
Name Description
entities Entity[]

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

Last updated 2025年11月19日 UTC.