A client for Cloud Datastore – A highly-scalable NoSQL database for web and mobile applications.
Here's a simple usage example for using google-cloud from App/Compute Engine. This example shows how to create a Datastore entity. For the complete source code see CreateEntity.java.
Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind");
Key key = keyFactory.newKey("keyName");
Entity entity = Entity.newBuilder(key)
.set("name", "John Doe")
.set("age", 30)
.set("access_time", Timestamp.now())
.build();
datastore.put(entity);
This second example shows how to get and update a Datastore entity if it exists. For the complete source code see UpdateEntity.java.
Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind");
Key key = keyFactory.newKey("keyName");
Entity entity = datastore.get(key);
if (entity != null) {
System.out.println("Updating access_time for " + entity.getString("name"));
entity = Entity.newBuilder(entity)
.set("access_time", Timestamp.now())
.build();
datastore.update(entity);
}
When using google-cloud from outside of App/Compute Engine, you have to specify a project ID and provide credentials. See Also: Google Cloud Datastore
Classes
AggregationQuery
An implementation of a Google Cloud Datastore Query that returns AggregationResults, It can be constructed by providing a nested query (StructuredQuery or GqlQuery) to run the aggregations on and a set of Aggregation.
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"));
}
See Also: Datastore queries
AggregationQuery.Builder
AggregationResult
Represents a result of an AggregationQuery query submission.
AggregationResults
The result of an AggregationQuery query submission. Contains a List<AggregationResult> and readTime Timestamp in it.
This can be used to iterate over an underlying List<AggregationResult> directly.
BaseDatastoreBatchWriter
Base class for DatastoreBatchWriter.
BaseEntity<K>
A base class for entities (key and properties). An entity is a Google Cloud Datastore persistent data object. An entity holds one or more properties, represented by a name (as String) and a value (as com.google.cloud.datastore.Value), and may be associated with a key. For a list of possible values see ValueType. See Also: Google Cloud Datastore Entities, Properties, and Keys
BaseEntity.Builder<K,B>
BaseKey
Base class for keys.
BaseKey.Builder<B>
Base class for key builders.
Blob
A Google Cloud Datastore Blob. This class is immutable. See Also: Google Cloud Datastore Entities, Properties, and Keys
BlobValue
BlobValue.Builder
BooleanValue
BooleanValue.Builder
Cursor
A Google Cloud Datastore cursor. The cursor can be used to as a starting point or an ending point for a Query
DatastoreOptions
DatastoreOptions.Builder
DatastoreOptions.DefaultDatastoreFactory
DatastoreOptions.DefaultDatastoreRpcFactory
DoubleValue
DoubleValue.Builder
Entity
An entity is the Google Cloud Datastore persistent data object for a specific key. An entity will always have a complete Key.
Entity.Builder
EntityQuery
An implementation of a Google Cloud Datastore entity query that can be constructed by providing all the specific query elements. See Also: Datastore queries
EntityQuery.Builder
A EntityQuery
builder for queries that return Entity results.
EntityValue
EntityValue.Builder
FullEntity<K>
A full entity is a BaseEntity that holds all the properties associated with a Datastore entity (as opposed to ProjectionEntity).
FullEntity.Builder<K>
GqlQuery<V>
A Google Cloud Datastore GQL query.
A usage example:
When the type of the results is known the preferred usage would be:
Query<Entity> query =
Query.newGqlQueryBuilder(Query.ResultType.ENTITY, "select * from kind").build();
QueryResults<Entity> results = datastore.run(query);
while (results.hasNext()) {
Entity entity = results.next();
...
}
When the type of the results is unknown you can use this approach:
Query query = Query.newGqlQueryBuilder("select __key__ from kind").build();
QueryResults results = datastore.run(query);
if (Key.class.isAssignableFrom(results.getResultClass())) {
QueryResults<Key> keys = (QueryResults<Key>) results;
while (keys.hasNext()) {
Key key = keys.next();
...
}
}
See Also: GQL Reference
GqlQuery.Builder<V>
A GQL query builder.
GqlQueryProtoPreparer
IncompleteKey
An incomplete key (without a name or id). This class is immutable.
IncompleteKey.Builder
Key
A key that is guaranteed to be complete and could be used to reference a Google Cloud Datastore Entity. This class is immutable. See Also: Google Cloud Datastore Entities, Properties, and Keys
Key.Builder
KeyFactory
A helper for creating keys for a specific Datastore, using its associated projectId and namespace.
KeyQuery
An implementation of a Google Cloud Datastore key-only query that can be constructed by providing all the specific query elements. See Also: Datastore queries
KeyQuery.Builder
A KeyQuery
builder for queries that return Key results.
KeyValue
KeyValue.Builder
LatLng
A Google Cloud Datastore LatLng (represented by latitude and longitude in degrees). This class is immutable. See Also: Google Cloud Datastore Entities, Properties, and Keys
LatLngValue
LatLngValue.Builder
ListValue
A Google Cloud Datastore list value. A list value is a list of Value objects.
ListValue.Builder
LongValue
LongValue.Builder
NullValue
NullValue.Builder
PathElement
Represents a single element in a key's path.
ProjectionEntity
A projection entity is a result of a Google Cloud Datastore projection query. A projection entity holds one or more properties, represented by a name (as String) and a value (as Value), and may have a Key. See Also: Google Cloud Datastore Entities, Properties, and Keys, Google Cloud Datastore projection queries
ProjectionEntity.Builder
ProjectionEntityQuery
An implementation of a Google Cloud Datastore projection entity query that can be constructed by providing all the specific query elements. See Also: Datastore queries
ProjectionEntityQuery.Builder
A ProjectionEntityQuery
builder for queries that return ProjectionEntity
results.
Query<V>
A Google Cloud Datastore query. For usage examples see GqlQuery, StructuredQuery and AggregationQuery.
Note that queries require proper indexing. See Cloud Datastore Index Configuration for help configuring indexes. See Also: Datastore Queries
Query.ResultType<V>
This class represents the expected type of the result. ENTITY: A full entity represented by Entity. PROJECTION_ENTITY: A projection entity, represented by ProjectionEntity. KEY: An entity's Key.
RawValue
RawValue.Builder
ReadOption
Specifies options for read operations in Datastore, namely getting/fetching entities and running queries.
ReadOption.EventualConsistency
Specifies eventual consistency for reads from Datastore. Lookups and ancestor queries using this option permit Datastore to return stale results.
ReadOption.QueryConfig<Q>
ReadOption.ReadTime
Reads entities as they were at the given time. This may not be older than 270 seconds. This value is only supported for Cloud Firestore in Datastore mode.
ReadOptionProtoPreparer
RetryAndTraceDatastoreRpcDecorator
An implementation of DatastoreRpc which acts as a Decorator and decorates the underlying DatastoreRpc with the logic of retry and Traceability.
StringValue
StringValue.Builder
StructuredQuery<V>
An implementation of a Google Cloud Datastore Query that can be constructed by providing all the specific query elements.
A usage example:
A simple query that returns all entities for a specific kind
Query<Entity> query = Query.newEntityQueryBuilder().setKind(kind).build();
QueryResults<Entity> results = datastore.run(query);
while (results.hasNext()) {
Entity entity = results.next();
...
}
A simple key-only query of all entities for a specific kind
Query<Key> keyOnlyQuery = Query.newKeyQueryBuilder().setKind(KIND1).build();
QueryResults<Key> results = datastore.run(keyOnlyQuery);
...
A less trivial example of a projection query that returns the first 10 results of "age" and "name" properties (sorted and grouped by "age") with an age greater than 18
Query<ProjectionEntity> query = Query.newProjectionEntityQueryBuilder()
.setKind(kind)
.setProjection(Projection.property("age"), Projection.first("name"))
.setFilter(PropertyFilter.gt("age", 18))
.setGroupBy("age")
.setOrderBy(OrderBy.asc("age"))
.setLimit(10)
.build();
QueryResults<ProjectionEntity> results = datastore.run(query);
...
See Also: Datastore queries
StructuredQuery.CompositeFilter
A class representing a filter composed of a combination of other filters.
StructuredQuery.Filter
StructuredQuery.OrderBy
StructuredQuery.OrderBy.Direction
StructuredQuery.PropertyFilter
A class representing a filter based on a single property or ancestor.
StructuredQueryProtoPreparer
TimestampValue
TimestampValue.Builder
TraceUtil
Helper class for tracing utility. It is used for instrumenting HttpDatastoreRpc with OpenCensus APIs.
TraceUtil instances are created by the TraceUtil#getInstance() method.
TransactionExceptionHandler
TransactionOperationExceptionHandler
Value<V>
Base class for all Google Cloud Datastore value types. All values must be associated with a non-null content (except NullValue). All values are immutable (including their content). To edit (a copy) use #toBuilder(). Unsupported value (deprecated or unrecognized) would be represented by RawValue.
Interfaces
Batch
An interface to represent a batch of write operations. Any write operation that is applied on a batch will only be sent to the Datastore upon #submit. A usage example:
Entity entity1 = datastore.get(key1);
Batch batch = datastore.newBatch();
Entity entity2 = Entity.newBuilder(key2).set("name", "John").build();
entity1 = Entity.newBuilder(entity1).clear().setNull("bla").build();
Entity entity3 = Entity.newBuilder(key3).set("title", "title").build();
batch.update(entity1);
batch.add(entity2, entity3);
batch.submit();
WARNING: This class maintains an internal state in terms of java.util.LinkedHashMap and java.util.LinkedHashSet which gets updated on every method call performing CRUD operations to record the mutations. Since java.util.LinkedHashMap is not thread safe as per its documentation, This class too should not be treated as a thread safe class.
Batch.Response
Datastore
An interface for Google Cloud Datastore.
Datastore.TransactionCallable<T>
A callback for running with a transactional com.google.cloud.datastore.DatastoreReaderWriter. The associated transaction will be committed
after a successful return from the run
method. Any propagated exception will cause the
transaction to be rolled-back.
DatastoreBatchWriter
An interface to represent a batch of write operations. All write operation for a batch writer will be applied to the Datastore in one RPC call.
WARNING: This class maintains an internal state in terms of java.util.LinkedHashMap and java.util.LinkedHashSet which gets updated on every method call performing CRUD operations to record the mutations. Since java.util.LinkedHashMap is not thread safe as per its documentation, This class too should not be treated as a thread safe class.
DatastoreFactory
An interface for Datastore factories.
DatastoreReader
An interface to represent Google Cloud Datastore read operations.
DatastoreReaderWriter
An interface that combines both Google Cloud Datastore read and write operations.
DatastoreWriter
An interface to represent Google Cloud Datastore write operations.
QueryResults<V>
The result of a Google Cloud Datastore query submission. When the result is not typed it is
possible to cast it to its appropriate type according to the #getResultClass value.
Results are loaded lazily in batches, where batch size is set by Cloud Datastore. As a result, it
is possible to get a DatastoreException
upon hasNext or next calls.
RecordQuery<V>
An internal marker interface to represent Query that returns the entity records.
StructuredQuery.Builder<V>
Interface for StructuredQuery builders.
Transaction
A Google cloud datastore transaction. Similar to Batch any write operation that is
applied on a transaction will only be sent to the Datastore upon #commit. A call to
#rollback will invalidate the transaction and discard the changes. Any read operation
that is done by a transaction will be part of it and therefore a commit
is guaranteed to
fail if an entity was modified outside the transaction after it was read. Write operation on this
transaction will not be reflected by read operation (as the changes are only sent to the
Datastore upon commit
. A usage example:
Transaction transaction = datastore.newTransaction();
try {
Entity entity = transaction.get(key);
if (!entity.contains("last_name") || entity.isNull("last_name")) {
String[] name = entity.getString("name").split(" ");
entity = Entity.newBuilder(entity)
.remove("name")
.set("first_name", name[0])
.set("last_name", name[1])
.build();
transaction.update(entity);
transaction.commit();
}
} finally {
if (transaction.isActive()) {
transaction.rollback();
}
}
See Also: Google Cloud Datastore transactions
WARNING: This class maintains an internal state in terms of java.util.LinkedHashMap and java.util.LinkedHashSet which gets updated on every method call performing CRUD operations to record the mutations. Since java.util.LinkedHashMap is not thread safe as per its documentation, This class too should not be treated as a thread safe class.
Transaction.Response
ValueBuilder<V,P,B>
A common interface for Value builders.
Enums
AggregationQuery.Mode
ValueType
The type of a Datastore property. See Also: Google Cloud Datastore types
Exceptions
DatastoreException
Datastore service exception. See Also: Google Cloud Datastore error codes