Interface Datastore
- All Superinterfaces:
DatastoreReader
,DatastoreReaderWriter
,DatastoreWriter
,com.google.cloud.Service<DatastoreOptions>
-
Nested Class Summary
Modifier and TypeInterfaceDescriptionstatic interface
A callback for running with a transactionalDatastoreReaderWriter
. -
Method Summary
Modifier and TypeMethodDescriptionadd
(FullEntity<?> entity) Datastore add operation: inserts the provided entity.add
(FullEntity<?>... entities) Datastore add operation: inserts the provided entities.allocateId
(IncompleteKey key) Allocate a unique id for the given key.allocateId
(IncompleteKey... keys) Returns a list of keys using the allocated ids ordered by the input.void
A datastore delete operation.fetch
(Iterable<Key> keys, ReadOption... options) Returns a list with a value for each given key (ordered by input).get
(Key key, ReadOption... options) get
(Iterable<Key> keys, ReadOption... options) newBatch()
Returns a new Batch for processing multiple write operations in one request.Returns a new KeyFactory for this serviceReturns a new Datastore transaction.newTransaction
(TransactionOptions options) Returns a new Datastore transaction.put
(FullEntity<?> entity) A Datastore put (a.k.a upsert) operation: inserts an entity if it does not exist, updates it otherwise.put
(FullEntity<?>... entities) A Datastore put (a.k.a upsert) operation: creates an entity if it does not exist, updates it otherwise.reserveIds
(Key... keys) Reserve one or more keys, preventing them from being automatically allocated by Datastore.<T> QueryResults<T>
run
(Query<T> query, ReadOption... options) Submits aQuery
and returns its result.default AggregationResults
runAggregation
(AggregationQuery query, ReadOption... options) Submits aAggregationQuery
and returnsAggregationResults
.<T> T
runInTransaction
(Datastore.TransactionCallable<T> callable) Invokes the callback'sDatastore.TransactionCallable.run(com.google.cloud.datastore.DatastoreReaderWriter)
method with aDatastoreReaderWriter
that is associated with a new transaction.<T> T
runInTransaction
(Datastore.TransactionCallable<T> callable, TransactionOptions options) Invokes the callback'sDatastore.TransactionCallable.run(com.google.cloud.datastore.DatastoreReaderWriter)
method with aDatastoreReaderWriter
that is associated with a new transaction.void
A Datastore update operation.Methods inherited from interface com.google.cloud.datastore.DatastoreReader
fetch, get, get, run, runAggregation
Methods inherited from interface com.google.cloud.Service
getOptions
-
Method Details
-
newTransaction
Returns a new Datastore transaction.- Parameters:
options
- a transaction option indicating the mode of the transaction (read-only or read-write)- Throws:
DatastoreException
- upon failure
-
newTransaction
Transaction newTransaction()Returns a new Datastore transaction.- Throws:
DatastoreException
- upon failure
-
runInTransaction
Invokes the callback'sDatastore.TransactionCallable.run(com.google.cloud.datastore.DatastoreReaderWriter)
method with aDatastoreReaderWriter
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 aDatastoreException
with the original exception as its root cause.Example of running in a transaction.
String callableResult = "my_callable_result"; TransactionCallable<String> callable = new TransactionCallable<String>() { public String run(DatastoreReaderWriter readerWriter) { // use readerWriter to run in transaction return callableResult; } }; String result = datastore.runInTransaction(callable);
- Parameters:
callable
- the callback to call with a newly created transactional readerWriter- Throws:
DatastoreException
- upon failure
-
runInTransaction
Invokes the callback'sDatastore.TransactionCallable.run(com.google.cloud.datastore.DatastoreReaderWriter)
method with aDatastoreReaderWriter
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 aDatastoreException
with the original exception as its root cause. IfTransactionOptions
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.
String callableResult = "my_callable_result"; TransactionCallable<String> callable = new TransactionCallable<String>() { public String run(DatastoreReaderWriter readerWriter) { // use readerWriter to run in transaction return callableResult; } }; TransactionOptions options = TransactionOptions.newBuilder() .setReadWrite(TransactionOptions.ReadWrite .getDefaultInstance()) .build(); String result = datastore.runInTransaction(callable, options);
- Parameters:
callable
- the callback to call with a newly created transactional readerWriteroptions
- the Transaction options indicating whether the transaction mode is Read-only or Read-Write- Throws:
DatastoreException
- upon failure
-
newBatch
Batch newBatch()Returns a new Batch for processing multiple write operations in one request.Example of starting a new batch.
String keyName1 = "my_key_name_1"; String keyName2 = "my_key_name_2"; Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); Batch batch = datastore.newBatch(); Entity entity1 = Entity.newBuilder(key1).set("name", "John").build(); Entity entity2 = Entity.newBuilder(key2).set("title", "title").build(); batch.add(entity1); batch.add(entity2); batch.submit();
-
allocateId
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.
KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); IncompleteKey incompleteKey = keyFactory.newKey(); // let cloud datastore automatically assign an id Key key = datastore.allocateId(incompleteKey);
- Throws:
DatastoreException
- upon failure
-
allocateId
Returns a list of keys using the allocated ids ordered by the input.Example of allocating multiple ids in a single batch.
KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); IncompleteKey incompleteKey1 = keyFactory.newKey(); IncompleteKey incompleteKey2 = keyFactory.newKey(); // let cloud datastore automatically assign the ids List<Key> keys = datastore.allocateId(incompleteKey1, incompleteKey2);
- Throws:
DatastoreException
- upon failure- See Also:
-
reserveIds
Reserve one or more keys, preventing them from being automatically allocated by Datastore.Example of reserving multiple ids in a single batch.
KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); Key key1 = keyFactory.newKey(10); Key key2 = keyFactory.newKey("name"); List<Key> keys = datastore.reserveIds(key1, key2);
- Throws:
DatastoreException
- upon failure
-
add
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, aDatastoreException
is thrown withBaseServiceException.getReason()
equal to"ALREADY_EXISTS"
.Example of adding a single entity.
String keyName = "my_key_name"; Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); Entity.Builder entityBuilder = Entity.newBuilder(key); entityBuilder.set("propertyName", "value"); Entity entity = entityBuilder.build(); try { datastore.add(entity); } catch (DatastoreException ex) { if ("ALREADY_EXISTS".equals(ex.getReason())) { // entity.getKey() already exists } }
- Specified by:
add
in interfaceDatastoreWriter
- Parameters:
entity
- the entity to add- Returns:
- an
Entity
with the same properties and a key that is either newly allocated or the same one if key is already complete - Throws:
DatastoreException
- upon failure or if an entity forentity.getKey()
already exists
-
add
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
withBaseServiceException.getReason()
equal to"ALREADY_EXISTS"
. All entities inentities
whose key did not exist are inserted. To achieve a transactional behavior, useTransaction
.Example of adding multiple entities.
String keyName1 = "my_key_name1"; String keyName2 = "my_key_name2"; Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); Entity.Builder entityBuilder1 = Entity.newBuilder(key1); entityBuilder1.set("propertyName", "value1"); Entity entity1 = entityBuilder1.build(); Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); Entity.Builder entityBuilder2 = Entity.newBuilder(key2); entityBuilder2.set("propertyName", "value2"); Entity entity2 = entityBuilder2.build(); try { datastore.add(entity1, entity2); } catch (DatastoreException ex) { if ("ALREADY_EXISTS".equals(ex.getReason())) { // at least one of entity1.getKey() and entity2.getKey() already exists } }
- Specified by:
add
in interfaceDatastoreWriter
- Returns:
- a list of
Entity
ordered by input with the same properties and a key that is either newly allocated or the same one if was already complete - Throws:
DatastoreException
- upon failure or if any of entities' keys already exists- See Also:
-
update
A Datastore update operation. The operation will fail if an entity with the same key does not already exist.Example of updating multiple entities.
String keyName1 = "my_key_name_1"; String keyName2 = "my_key_name_2"; Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); Entity.Builder entityBuilder1 = Entity.newBuilder(key1); entityBuilder1.set("propertyName", "updatedValue1"); Entity entity1 = entityBuilder1.build(); Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); Entity.Builder entityBuilder2 = Entity.newBuilder(key2); entityBuilder2.set("propertyName", "updatedValue2"); Entity entity2 = entityBuilder2.build(); datastore.update(entity1, entity2);
- Specified by:
update
in interfaceDatastoreWriter
- Throws:
DatastoreException
- upon failure
-
put
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.
String keyName = "my_key_name"; Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); Entity.Builder entityBuilder = Entity.newBuilder(key); entityBuilder.set("propertyName", "value"); Entity entity = entityBuilder.build(); datastore.put(entity);
- Specified by:
put
in interfaceDatastoreWriter
- Parameters:
entity
- the entity to put- Returns:
- an
Entity
with the same properties and a key that is either newly allocated or the same one if key is already complete - Throws:
DatastoreException
- upon failure
-
put
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.
String keyName1 = "my_key_name1"; String keyName2 = "my_key_name2"; Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); Entity.Builder entityBuilder1 = Entity.newBuilder(key1); entityBuilder1.set("propertyName", "value1"); Entity entity1 = entityBuilder1.build(); Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); Entity.Builder entityBuilder2 = Entity.newBuilder(key2); entityBuilder2.set("propertyName", "value2"); Entity entity2 = entityBuilder2.build(); datastore.put(entity1, entity2);
- Specified by:
put
in interfaceDatastoreWriter
- Returns:
- a list of updated or inserted
Entity
, ordered by input. Returned keys are either newly allocated or the same one if was already complete. - Throws:
DatastoreException
- upon failure
-
delete
A datastore delete operation. It is OK to request the deletion of a non-existing key.Example of deleting multiple entities.
String keyName1 = "my_key_name1"; String keyName2 = "my_key_name2"; Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); datastore.delete(key1, key2);
- Specified by:
delete
in interfaceDatastoreWriter
- Throws:
DatastoreException
- upon failure
-
newKeyFactory
KeyFactory newKeyFactory()Returns a new KeyFactory for this serviceExample of creating a
KeyFactory
.KeyFactory keyFactory = datastore.newKeyFactory();
-
get
Returns anEntity
for the givenKey
ornull
if it doesn't exist.ReadOption
s can be specified if desired.Example of getting an entity.
String keyName = "my_key_name"; Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); Entity entity = datastore.get(key); // Do something with the entity
- Throws:
DatastoreException
- upon failure
-
get
Returns anEntity
for each givenKey
that exists in the Datastore. The order of the result is unspecified. Results are loaded lazily, so it is possible to get aDatastoreException
from the returnedIterator
'shasNext
ornext
methods.ReadOption
s can be specified if desired.Example of getting multiple entity objects.
String firstKeyName = "my_first_key_name"; String secondKeyName = "my_second_key_name"; KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); Key firstKey = keyFactory.newKey(firstKeyName); Key secondKey = keyFactory.newKey(secondKeyName); Iterator<Entity> entitiesIterator = datastore.get(Lists.newArrayList(firstKey, secondKey)); List<Entity> entities = Lists.newArrayList(); while (entitiesIterator.hasNext()) { Entity entity = entitiesIterator.next(); // do something with the entity entities.add(entity); }
- Throws:
DatastoreException
- upon failure- See Also:
-
fetch
Returns a list with a value for each given key (ordered by input).null
values are returned for nonexistent keys. When possible prefer usingDatastoreReader.get(Key...)
to avoid eagerly loading the results.ReadOption
s can be specified if desired.Example of fetching a list of Entity objects.
String firstKeyName = "my_first_key_name"; String secondKeyName = "my_second_key_name"; KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); Key firstKey = keyFactory.newKey(firstKeyName); Key secondKey = keyFactory.newKey(secondKeyName); List<Entity> entities = datastore.fetch(Lists.newArrayList(firstKey, secondKey)); for (Entity entity : entities) { // do something with the entity }
-
run
Submits aQuery
and returns its result.ReadOption
s can be specified if desired.Example of running a query to find all entities of one kind.
String kind = "my_kind"; StructuredQuery<Entity> query = Query.newEntityQueryBuilder() .setKind(kind) .build(); QueryResults<Entity> results = datastore.run(query); List<Entity> entities = Lists.newArrayList(); while (results.hasNext()) { Entity result = results.next(); // do something with result entities.add(result); }
Example of running a query to find all entities with a matching property value.
String kind = "my_kind"; String property = "my_property"; String value = "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()) { Entity result = results.next(); // do something with result entities.add(result); }
- Throws:
DatastoreException
- upon failure
-
runAggregation
Submits aAggregationQuery
and returnsAggregationResults
.ReadOption
s can be specified if desired.Example of running an
AggregationQuery
to find the count of entities of one kind.StructuredQuery
example:EntityQuery selectAllQuery = Query.newEntityQueryBuilder() .setKind("Task") .build(); AggregationQuery aggregationQuery = Query.newAggregationQueryBuilder() .addAggregation(count().as("total_count")) .over(selectAllQuery) .build(); AggregationResults aggregationResults = datastore.runAggregation(aggregationQuery); for (AggregationResult aggregationResult : aggregationResults) { System.out.println(aggregationResult.get("total_count")); }
GqlQuery
example:GqlQuery<?> selectAllGqlQuery = Query.newGqlQueryBuilder( "AGGREGATE COUNT(*) AS total_count, COUNT_UP_TO(100) AS count_upto_100 OVER(SELECT * FROM Task)" ) .setAllowLiteral(true) .build(); AggregationQuery aggregationQuery = Query.newAggregationQueryBuilder() .over(selectAllGqlQuery) .build(); AggregationResults aggregationResults = datastore.runAggregation(aggregationQuery); for (AggregationResult aggregationResult : aggregationResults) { System.out.println(aggregationResult.get("total_count")); System.out.println(aggregationResult.get("count_upto_100")); }
- Returns:
AggregationResults
- Throws:
DatastoreException
- upon failure
-