Java idiomatic client for Cloud Datastore.
If you are using Maven with BOM, add this to your pom.xml file:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>26.27.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-datastore</artifactId>
</dependency>
If you are using Maven without the BOM, add this to your dependencies:
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-datastore</artifactId>
<version>2.17.5</version>
</dependency>
If you are using Gradle 5.x or later, add this to your dependencies:
implementation platform('com.google.cloud:libraries-bom:26.27.0')
implementation 'com.google.cloud:google-cloud-datastore'
If you are using Gradle without BOM, add this to your dependencies:
implementation 'com.google.cloud:google-cloud-datastore:2.17.5'
If you are using SBT, add this to your dependencies:
libraryDependencies += "com.google.cloud" % "google-cloud-datastore" % "2.17.5"
See the Authentication section in the base directory's README.
The client application making API calls must be granted authorization scopes required for the desired Cloud Datastore APIs, and the authenticated principal must have the IAM role(s) required to access GCP resources using the Cloud Datastore API calls.
You will need a Google Cloud Platform Console project with the Cloud Datastore API enabled.
Follow these instructions to get your project set up. You will also need to set up the local development environment by
installing the Google Cloud Command Line Interface and running the following commands in command line:
gcloud auth login
and gcloud config set project [YOUR PROJECT ID]
.
You'll need to obtain the google-cloud-datastore
library. See the Quickstart section
to add google-cloud-datastore
as a dependency in your code.
Cloud Datastore is a fully managed, schemaless database for storing non-relational data. Cloud Datastore automatically scales with your users and supports ACID transactions, high availability of reads and writes, strong consistency for reads and ancestor queries, and eventual consistency for all other queries.
See the Cloud Datastore client library docs to learn how to use this Cloud Datastore Client Library.
See the [Google Cloud Datastore docs][cloud-datastore-activation] for more details on how to activate Cloud Datastore for your project.
See the [Datastore client library docs][datastore-client-lib-docs] to learn how to interact with the Cloud Datastore using this Client Library.
To make authenticated requests to Google Cloud Datastore, you must create a service object with credentials. You can then make API calls by calling methods on the Datastore service object. The simplest way to authenticate is to use Application Default Credentials. These credentials are automatically inferred from your environment, so you only need the following code to create your service object:
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
For other authentication options, see the Authentication page.
Objects in Datastore are known as entities. Entities are grouped by "kind" and have keys for easy access. In this code snippet, we will create a new entity representing a person and store that data by the person's email. First, add the following imports at the top of your file:
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.KeyFactory;
Then add the following code to put an entity in Datastore.
KeyFactory keyFactory = datastore.newKeyFactory().setKind("Person");
Key key = keyFactory.newKey("[email protected]");
Entity entity = Entity.newBuilder(key)
.set("name", "John Doe")
.set("age", 51)
.set("favorite_food", "pizza")
.build();
datastore.put(entity);
Later, if you want to get this entity back, add the following to your code:
Entity johnEntity = datastore.get(key);
In addition to retrieving entities by their keys, you can perform queries to retrieve entities by
the values of their properties. A typical query includes an entity kind, filters to select entities
with matching values, and sort orders to sequence the results. google-cloud-datastore
supports two
types of queries: StructuredQuery
(that allows you to construct query elements) and GqlQuery
(which operates using GQL syntax)
in string format. In this tutorial, we will use a simple StructuredQuery
.
Suppose that you've added more people to Datastore, and now you want to find all people whose favorite food is pizza. Import the following:
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.QueryResults;
import com.google.cloud.datastore.StructuredQuery;
import com.google.cloud.datastore.StructuredQuery.PropertyFilter;
Then add the following code to your program:
Query<Entity> query = Query.newEntityQueryBuilder()
.setKind("Person")
.setFilter(PropertyFilter.eq("favorite_food", "pizza"))
.build();
QueryResults<Entity> results = datastore.run(query);
while (results.hasNext()) {
Entity currentEntity = results.next();
System.out.println(currentEntity.getString("name") + ", you're invited to a pizza party!");
}
Cloud Datastore relies on indexing to run queries. Indexing is turned on by default for most types of properties. To read more about indexing, see the Cloud Datastore Index Configuration documentation.
Another thing you'll probably want to do is update your data. The following snippet shows how to update a Datastore entity if it exists.
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", DateTime.now())
.build();
datastore.update(entity);
}
The complete source code can be found at UpdateEntity.java.
In AddEntitiesAndRunQuery.java we put together all the code to store data and run queries into one program. The program assumes that you are running on Compute Engine or from your own desktop. To run the example on App Engine, simply move the code from the main method to your application's servlet class and change the print statements to display on your webpage.
This library has tools to help write tests for code that uses the Datastore.
You can test against a temporary local Datastore by following these steps:
To determine which host/port the emulator is running on:
$ gcloud beta emulators datastore env-init
# Sample output:
# export DATASTORE_EMULATOR_HOST=localhost:8759
- Point your client to the emulator
DatastoreOptions options = DatastoreOptions.newBuilder()
.setProjectId(DatastoreOptions.getDefaultProjectId())
.setHost(System.getenv("DATASTORE_EMULATOR_HOST"))
.setCredentials(NoCredentials.getInstance())
.setRetrySettings(ServiceOptions.getNoRetrySettings())
.build();
Datastore datastore = options.getService();
- Run your tests
Bookshelf
- An App Engine app that manages a virtual bookshelf.- This app uses
google-cloud
to interface with Cloud Datastore and Cloud Storage. It also uses Cloud SQL, another Google Cloud Platform service.
- This app uses
Flexible Environment/Datastore example
- A simple app that uses Cloud Datastore to list the last 10 IP addresses that visited your site.SparkDemo
- An example of usinggoogle-cloud-datastore
from within the SparkJava and App Engine Flexible Environment frameworks.- Read about how it works on the example's README page.
Samples are in the samples/
directory.
Sample | Source Code | Try it |
---|---|---|
Native Image Datastore Sample | source code | |
Quickstart Sample | source code | |
Avg Aggregation On Kind | source code | |
Avg Aggregation With Limit | source code | |
Avg Aggregation With Order By | source code | |
Avg Aggregation With Property Filter | source code | |
Count Aggregation In Transaction | source code | |
Count Aggregation On Kind | source code | |
Count Aggregation With Gql Query | source code | |
Count Aggregation With Limit | source code | |
Count Aggregation With Order By | source code | |
Count Aggregation With Property Filter | source code | |
Count Aggregation With Stale Read | source code | |
Multiple Aggregations In Gql Query | source code | |
Multiple Aggregations In Structured Query | source code | |
Sum Aggregation On Kind | source code | |
Sum Aggregation With Limit | source code | |
Sum Aggregation With Order By | source code | |
Sum Aggregation With Property Filter | source code | |
Create a union between two filters | source code | |
Task List | source code |
To get help, follow the instructions in the shared Troubleshooting document.
Java 8 or above is required for using this client.
Google's Java client libraries, Google Cloud Client Libraries and Google Cloud API Libraries, follow the Oracle Java SE support roadmap (see the Oracle Java SE Product Releases section).
In general, new feature development occurs with support for the lowest Java LTS version covered by Oracle's Premier Support (which typically lasts 5 years from initial General Availability). If the minimum required JVM for a given library is changed, it is accompanied by a semver major release.
Java 11 and (in September 2021) Java 17 are the best choices for new development.
Google tests its client libraries with all current LTS versions covered by Oracle's Extended Support (which typically lasts 8 years from initial General Availability).
Google's client libraries support legacy versions of Java runtimes with long term stable libraries that don't receive feature updates on a best efforts basis as it may not be possible to backport all patches.
Google provides updates on a best efforts basis to apps that continue to use Java 7, though apps might need to upgrade to current versions of the library that supports their JVM.
The latest versions and the supported Java versions are identified on
the individual GitHub repository github.com/GoogleAPIs/java-SERVICENAME
and on google-cloud-java.
This library follows Semantic Versioning.
Contributions to this library are always welcome and highly encouraged.
See CONTRIBUTING for more information how to get started.
Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See Code of Conduct for more information.
Apache 2.0 - See LICENSE for more information.
Java Version | Status |
---|---|
Java 8 | |
Java 8 OSX | |
Java 8 Windows | |
Java 11 |
Java is a registered trademark of Oracle and/or its affiliates.