Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

License

NotificationsYou must be signed in to change notification settings

kolea2/java-datastore

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1,370 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Java idiomatic client forCloud Datastore.

MavenStability

Quickstart

If you are using Maven withBOM, add this to your pom.xml file:

<dependencyManagement>  <dependencies>    <dependency>      <groupId>com.google.cloud</groupId>      <artifactId>libraries-bom</artifactId>      <version>26.35.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.19.0</version></dependency>

If you are using Gradle 5.x or later, add this to your dependencies:

implementation platform('com.google.cloud:libraries-bom:26.35.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.19.0'

If you are using SBT, add this to your dependencies:

libraryDependencies+="com.google.cloud"%"google-cloud-datastore"%"2.19.0"

Authentication

See theAuthentication section in the base directory's README.

Authorization

The client application making API calls must be grantedauthorization scopes required for the desired Cloud Datastore APIs, and the authenticated principal must have theIAM role(s) required to access GCP resources using the Cloud Datastore API calls.

Getting Started

Prerequisites

You will need aGoogle Cloud Platform Console project with the Cloud DatastoreAPI enabled.

Follow these instructions to get your project set up. You will also need to set up the local development environment byinstalling the Google Cloud Command Line Interface and running the following commands in command line:gcloud auth login andgcloud config set project [YOUR PROJECT ID].

Installation and setup

You'll need to obtain thegoogle-cloud-datastore library. See theQuickstart sectionto addgoogle-cloud-datastore as a dependency in your code.

About Cloud Datastore

Cloud Datastore is a fully managed, schemaless database forstoring non-relational data. Cloud Datastore automatically scales withyour users and supports ACID transactions, high availability of reads andwrites, strong consistency for reads and ancestor queries, and eventualconsistency for all other queries.

See theCloud Datastore client library docs to learn how touse this Cloud Datastore Client Library.

See the [Google Cloud Datastore docs][cloud-datastore-activation] for more details on how to activateCloud Datastore for your project.

See the [Datastore client library docs][datastore-client-lib-docs] to learn how to interactwith the Cloud Datastore using this Client Library.

Creating an authorized service object

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 useApplication Default Credentials. These credentials are automatically inferred from your environment, so you only need the following code to create your service object:

importcom.google.cloud.datastore.Datastore;importcom.google.cloud.datastore.DatastoreOptions;Datastoredatastore =DatastoreOptions.getDefaultInstance().getService();

For other authentication options, see theAuthentication page.

Storing data

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:

importcom.google.cloud.datastore.Entity;importcom.google.cloud.datastore.Key;importcom.google.cloud.datastore.KeyFactory;

Then add the following code to put an entity in Datastore.

KeyFactorykeyFactory =datastore.newKeyFactory().setKind("Person");Keykey =keyFactory.newKey("john.doe@gmail.com");Entityentity =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:

EntityjohnEntity =datastore.get(key);

Running a query

In addition to retrieving entities by their keys, you can perform queries to retrieve entities bythe values of their properties. A typical query includes an entity kind, filters to select entitieswith matching values, and sort orders to sequence the results.google-cloud-datastore supports twotypes of queries:StructuredQuery (that allows you to construct query elements) andGqlQuery(which operates usingGQL syntax)in string format. In this tutorial, we will use a simpleStructuredQuery.

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:

importcom.google.cloud.datastore.Query;importcom.google.cloud.datastore.QueryResults;importcom.google.cloud.datastore.StructuredQuery;importcom.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()) {EntitycurrentEntity =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 theCloud Datastore Index Configuration documentation.

Updating data

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.

KeyFactorykeyFactory =datastore.newKeyFactory().setKind("keyKind");Keykey =keyFactory.newKey("keyName");Entityentity =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 atUpdateEntity.java.

Complete source code

InAddEntitiesAndRunQuery.javawe put together all the code to store data and run queries into one program. The program assumes that you arerunning on Compute Engine or from your own desktop. To run the example on App Engine, simply movethe code from the main method to your application's servlet class and change the print statements todisplay on your webpage.

Testing

This library has tools to help write tests for code that uses the Datastore.

On your machine

You can test against a temporary local Datastore by following these steps:

  1. Install Cloud SDK and start the emulator

To determine which host/port the emulator is running on:

$ gcloud beta emulators datastore env-init# Sample output:#   export DATASTORE_EMULATOR_HOST=localhost:8759
  1. Point your client to the emulator
DatastoreOptionsoptions =DatastoreOptions.newBuilder().setProjectId(DatastoreOptions.getDefaultProjectId()).setHost(System.getenv("DATASTORE_EMULATOR_HOST")).setCredentials(NoCredentials.getInstance()).setRetrySettings(ServiceOptions.getNoRetrySettings()).build();Datastoredatastore =options.getService();
  1. Run your tests

Example Applications

  • Bookshelf - An App Engine app that manages a virtual bookshelf.
    • This app usesgoogle-cloud to interface with Cloud Datastore and Cloud Storage. It also uses Cloud SQL, another Google Cloud Platform service.
  • 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.

Samples

Samples are in thesamples/ directory.

SampleSource CodeTry it
Native Image Datastore Samplesource codeOpen in Cloud Shell
Quickstart Samplesource codeOpen in Cloud Shell
Avg Aggregation On Kindsource codeOpen in Cloud Shell
Avg Aggregation With Limitsource codeOpen in Cloud Shell
Avg Aggregation With Order Bysource codeOpen in Cloud Shell
Avg Aggregation With Property Filtersource codeOpen in Cloud Shell
Count Aggregation In Transactionsource codeOpen in Cloud Shell
Count Aggregation On Kindsource codeOpen in Cloud Shell
Count Aggregation With Gql Querysource codeOpen in Cloud Shell
Count Aggregation With Limitsource codeOpen in Cloud Shell
Count Aggregation With Order Bysource codeOpen in Cloud Shell
Count Aggregation With Property Filtersource codeOpen in Cloud Shell
Count Aggregation With Stale Readsource codeOpen in Cloud Shell
Multiple Aggregations In Gql Querysource codeOpen in Cloud Shell
Multiple Aggregations In Structured Querysource codeOpen in Cloud Shell
Sum Aggregation On Kindsource codeOpen in Cloud Shell
Sum Aggregation With Limitsource codeOpen in Cloud Shell
Sum Aggregation With Order Bysource codeOpen in Cloud Shell
Sum Aggregation With Property Filtersource codeOpen in Cloud Shell
Create a union between two filterssource codeOpen in Cloud Shell
Query Profile Explainsource codeOpen in Cloud Shell
Query Profile Explain Aggregationsource codeOpen in Cloud Shell
Query Profile Explain Analyzesource codeOpen in Cloud Shell
Query Profile Explain Analyze Aggregationsource codeOpen in Cloud Shell
Task Listsource codeOpen in Cloud Shell

Troubleshooting

To get help, follow the instructions in theshared Troubleshooting document.

Supported Java Versions

Java 8 or above is required for using this client.

Google's Java client libraries,Google Cloud Client LibrariesandGoogle Cloud API Libraries,follow theOracle Java SE support roadmap(see the Oracle Java SE Product Releases section).

For new development

In general, new feature development occurs with support for the lowest JavaLTS version covered by Oracle's Premier Support (which typically lasts 5 yearsfrom initial General Availability). If the minimum required JVM for a givenlibrary is changed, it is accompanied by asemver major release.

Java 11 and (in September 2021) Java 17 are the best choices for newdevelopment.

Keeping production systems current

Google tests its client libraries with all current LTS versions covered byOracle's Extended Support (which typically lasts 8 years from initialGeneral Availability).

Legacy support

Google's client libraries support legacy versions of Java runtimes with longterm stable libraries that don't receive feature updates on a best efforts basisas it may not be possible to backport all patches.

Google provides updates on a best efforts basis to apps that continue to useJava 7, though apps might need to upgrade to current versions of the librarythat supports their JVM.

Where to find specific information

The latest versions and the supported Java versions are identified onthe individual GitHub repositorygithub.com/GoogleAPIs/java-SERVICENAMEand ongoogle-cloud-java.

Versioning

This library followsSemantic Versioning.

Contributing

Contributions to this library are always welcome and highly encouraged.

SeeCONTRIBUTING for more information how to get started.

Please note that this project is released with a Contributor Code of Conduct. By participating inthis project you agree to abide by its terms. SeeCode of Conduct for moreinformation.

License

Apache 2.0 - SeeLICENSE for more information.

CI Status

Java VersionStatus
Java 8Kokoro CI
Java 8 OSXKokoro CI
Java 8 WindowsKokoro CI
Java 11Kokoro CI

Java is a registered trademark of Oracle and/or its affiliates.

About

No description, website, or topics provided.

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Java99.7%
  • Other0.3%

[8]ページ先頭

©2009-2026 Movatter.jp