Cloud Datastore Client Libraries

This page shows how to get started with the new Cloud Client Libraries for the Google Cloud Datastore API. Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

Installing the client library

C#

Install-Package Google.Cloud.Datastore.V1

Go

go get -u cloud.google.com/go/datastore

Java

If you are using Maven, add this to your pom.xml file:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-datastore</artifactId>
  <version>1.6.0</version>
</dependency>
If you are using Gradle, add this to your dependencies:
compile 'com.google.cloud:google-cloud-datastore:1.6.0'
If you are using SBT, add this to your dependences:
libraryDependencies += "com.google.cloud" % "google-cloud-datastore" % "1.6.0"

Node.js

npm install --save @google-cloud/datastore

PHP

composer require google/cloud-datastore

Python

pip install --upgrade google-cloud-datastore

Ruby

gem install google-cloud-datastore

Using the client library

The following example shows how to use the client library. To run it on your local workstation you must first install the Google Cloud SDK and authenticate by running the following command:

gcloud auth application-default login

For information about authenticating in other environments, see setting up authentication for server to server production applications.

C#

using Google.Cloud.Datastore.V1;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static void Main(string[] args)
        {
            // Your Google Cloud Platform project ID
            string projectId = "YOUR-PROJECT-ID";

            // Instantiates a client
            DatastoreDb db = DatastoreDb.Create(projectId);

            // The kind for the new entity
            string kind = "Task";
            // The name/ID for the new entity
            string name = "sampletask1";
            KeyFactory keyFactory = db.CreateKeyFactory(kind);
            // The Cloud Datastore key for the new entity
            Key key = keyFactory.CreateKey(name);

            var task = new Entity
            {
                Key = key,
                ["description"] = "Buy milk"
            };
            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                // Saves the task
                transaction.Upsert(task);
                transaction.Commit();

                Console.WriteLine($"Saved {task.Key.Path[0].Name}: {(string)task["description"]}");
            }
        }
    }
}
Read more in the C# API Reference Documentation for the Google Cloud Datastore API Client Library.

Go

// Sample datastore-quickstart fetches an entity from Google Cloud Datastore.
package main

import (
	"fmt"
	"log"

	// Imports the Google Cloud Datastore client package.
	"cloud.google.com/go/datastore"
	"golang.org/x/net/context"
)

type Task struct {
	Description string
}

func main() {
	ctx := context.Background()

	// Set your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	// Creates a client.
	client, err := datastore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Sets the kind for the new entity.
	kind := "Task"
	// Sets the name/ID for the new entity.
	name := "sampletask1"
	// Creates a Key instance.
	taskKey := datastore.NameKey(kind, name, nil)

	// Creates a Task instance.
	task := Task{
		Description: "Buy milk",
	}

	// Saves the new entity.
	if _, err := client.Put(ctx, taskKey, &task); err != nil {
		log.Fatalf("Failed to save task: %v", err)
	}

	fmt.Printf("Saved %v: %v\n", taskKey, task.Description)
}
Read more in the Go API Reference Documentation for the Google Cloud Datastore API Client Library.

Java

// Imports the Google Cloud client library
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Datastore datastore = DatastoreOptions.getDefaultInstance().getService();

    // The kind for the new entity
    String kind = "Task";
    // The name/ID for the new entity
    String name = "sampletask1";
    // The Cloud Datastore key for the new entity
    Key taskKey = datastore.newKeyFactory().setKind(kind).newKey(name);

    // Prepares the new entity
    Entity task = Entity.newBuilder(taskKey)
        .set("description", "Buy milk")
        .build();

    // Saves the entity
    datastore.put(task);

    System.out.printf("Saved %s: %s%n", task.getKey().getName(), task.getString("description"));

    //Retrieve entity
    Entity retrieved = datastore.get(taskKey);

    System.out.printf("Retrieved %s: %s%n", taskKey.getName(), retrieved.getString("description"));

  }
}
Read more in the Java API Reference Documentation for the Google Cloud Datastore API Client Library.

Node.js

// Imports the Google Cloud client library
const Datastore = require('@google-cloud/datastore');

// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Instantiates a client
const datastore = Datastore({
  projectId: projectId
});

// The kind for the new entity
const kind = 'Task';
// The name/ID for the new entity
const name = 'sampletask1';
// The Cloud Datastore key for the new entity
const taskKey = datastore.key([kind, name]);

// Prepares the new entity
const task = {
  key: taskKey,
  data: {
    description: 'Buy milk'
  }
};

// Saves the entity
datastore.save(task)
  .then(() => {
    console.log(`Saved ${task.key.name}: ${task.data.description}`);
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });
Read more in the Node.js API Reference Documentation for the Google Cloud Datastore API Client Library.

PHP

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use Google\Cloud\Datastore\DatastoreClient;

# Your Google Cloud Platform project ID
$projectId = 'YOUR_PROJECT_ID';

# Instantiates a client
$datastore = new DatastoreClient([
    'projectId' => $projectId
]);

# The kind for the new entity
$kind = 'Task';

# The name/ID for the new entity
$name = 'sampletask1';

# The Cloud Datastore key for the new entity
$taskKey = $datastore->key($kind, $name);

# Prepares the new entity
$task = $datastore->entity($taskKey, ['description' => 'Buy milk']);

# Saves the entity
$datastore->upsert($task);

echo 'Saved ' . $task->key() . ': ' . $task['description'] . PHP_EOL;
Read more in the PHP API Reference Documentation for the Google Cloud Datastore API Client Library.

Python

# Imports the Google Cloud client library
from google.cloud import datastore

# Instantiates a client
datastore_client = datastore.Client()

# The kind for the new entity
kind = 'Task'
# The name/ID for the new entity
name = 'sampletask1'
# The Cloud Datastore key for the new entity
task_key = datastore_client.key(kind, name)

# Prepares the new entity
task = datastore.Entity(key=task_key)
task['description'] = 'Buy milk'

# Saves the entity
datastore_client.put(task)

print('Saved {}: {}'.format(task.key.name, task['description']))
Read more in the Python API Reference Documentation for the Google Cloud Datastore API Client Library.

Ruby

# Imports the Google Cloud client library
require "google/cloud/datastore"

# Your Google Cloud Platform project ID
project_id = "YOUR_PROJECT_ID"

# Instantiates a client
datastore = Google::Cloud::Datastore.new project: project_id

# The kind for the new entity
kind = "Task"
# The name/ID for the new entity
name = "sampletask1"
# The Cloud Datastore key for the new entity
task_key = datastore.key kind, name

# Prepares the new entity
task = datastore.entity task_key do |t|
  t["description"] = "Buy milk"
end

# Saves the entity
datastore.save task

puts "Saved #{task.key.name}: #{task['description']}"
Read more in the Ruby API Reference Documentation for the Google Cloud Datastore API Client Library.

Additional Resources

Dependency on App Engine application

If you are using a Google Cloud library to access Cloud Datastore, your Cloud project requires an active Google App Engine application. Open the App Engine dashboard and confirm your Cloud project has an active Google App Engine app. Create an App Engine app if needed. The app must not be disabled.

Google App Engine Standard Environment Client Libraries

Integrate Cloud Datastore with your App Engine Standard Environment applications by using the App Engine client libraries.

Language Library
Go Google App Engine SDK for Go
Java Google App Engine SDK for Java
Python Google Datastore NDB Client Library

Third party Datastore API client libraries

In addition to the Google-supported client libraries listed in the tables above, a set of third-party libraries are available.

Language Library
Java Objectify
Java Catatumbo
PHP Datastore Library for PHP
Node.js js-data-cloud-datastore

外出先でもリソースをモニタリング

Google Cloud Console アプリを入手して、プロジェクトの管理にお役立てください。

フィードバックを送信...

Cloud Datastore Documentation