Datastore mode Client Libraries

This page shows how to get started with the Cloud Client Libraries for the 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#

For more information, see Setting Up a C# Development Environment.

Install-Package Google.Cloud.Datastore.V1

Go

For more information, see Setting Up a Go Development Environment.

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

Java

For more information, see Setting Up a Java Development Environment.

Si vous utilisez Maven, ajoutez les lignes suivantes à votre fichier pom.xml. Pour en savoir plus sur les BOM, consultez la page The Google Cloud Platform Libraries BOM (BOM des bibliothèques Google Cloud Platform).

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>13.3.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-datastore</artifactId>
  </dependency>

Si vous utilisez Gradle, ajoutez les éléments suivants à vos dépendances :

compile 'com.google.cloud:google-cloud-datastore:1.105.1'

Si vous utilisez sbt, ajoutez les éléments suivants à vos dépendances :

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

Si vous utilisez IntelliJ ou Eclipse, vous pouvez ajouter des bibliothèques clientes à votre projet à l'aide des plug-ins IDE suivants :

Les plug-ins offrent des fonctionnalités supplémentaires, telles que la gestion des clés pour les comptes de service. Reportez-vous à la documentation de chaque plug-in pour plus de détails.

Node.js

For more information, see Setting Up a Node.js Development Environment.

npm install --save @google-cloud/datastore

PHP

For more information, see Using PHP on Google Cloud.

composer require google/cloud-datastore

Python

For more information, see Setting Up a Python Development Environment.

pip install --upgrade google-cloud-datastore

Ruby

For more information, see Setting Up a Ruby Development Environment.

gem install google-cloud-datastore

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For other ways to authenticate, see the GCP authentication documentation.

Cloud Console

  1. Dans Cloud Console, accédez à la page Créer une clé de compte de service.

    Accéder à la page "Créer une clé de compte de service"
  2. Dans la liste Compte de service, sélectionnez Nouveau compte de service.
  3. Dans le champ Nom du compte de service, saisissez un nom.
  4. Dans la liste Rôle, sélectionnez Projet > Propriétaire

  5. Cliquez sur Créer. Un fichier JSON contenant votre clé est téléchargé sur votre ordinateur.

Ligne de commande

Vous pouvez exécuter les commandes suivantes à l'aide du SDK Cloud sur votre ordinateur local, ou dans Cloud Shell.

  1. Créez le compte de service. Remplacez NAME par le nom que vous souhaitez donner au compte de service.

    gcloud iam service-accounts create NAME
  2. Accordez des autorisations au compte de service. Remplacez PROJECT_ID par votre ID de projet.

    gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:NAME@PROJECT_ID.iam.gserviceaccount.com" --role="roles/owner"
  3. Générez le fichier de clé. Remplacez FILE_NAME par le nom du fichier de clé.

    gcloud iam service-accounts keys create FILE_NAME.json --iam-account=NAME@PROJECT_ID.iam.gserviceaccount.com

Fournissez des identifiants d'authentification au code de votre application en définissant la variable d'environnement GOOGLE_APPLICATION_CREDENTIALS. Remplacez [PATH] par le chemin du fichier JSON contenant la clé de votre compte de service. Cette variable ne s'applique qu'à la session d'interface système actuelle. Par conséquent, si vous ouvrez une nouvelle session, vous devez la définir à nouveau.

Linux ou macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Exemple :

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"

Windows

Avec PowerShell :

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Exemple :

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\my-key.json"

Avec l'invite de commande :

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C#

Before trying this sample, follow the C# setup instructions in Setting Up a C# Development Environment. For more information, see the Datastore mode C# API reference documentation.

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"]}");
            }
        }
    }
}

Go

To use this sample, prepare your machine for Go development, and complete the Datastore mode quickstart. For more information, see the Datastore mode Go API reference documentation.


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

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/datastore"
)

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)
}

Java

Before trying this sample, follow the Java setup instructions in Setting Up a Java Development Environment. For more information, see the Datastore mode Java API reference documentation.

// 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"));

  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in Setting Up a Node.js Development Environment. For more information, see the Datastore mode Node.js API reference documentation.

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

// Creates a client
const datastore = new Datastore();

async function quickstart() {
  // 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
  await datastore.save(task);
  console.log(`Saved ${task.key.name}: ${task.data.description}`);
}
quickstart();

PHP

To use this sample, prepare your machine for PHP development, and complete the Datastore mode quickstart. For more information, see the Datastore mode PHP API reference documentation.

# 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;

Python

Before trying this sample, follow the Python setup instructions in Setting Up a Python Development Environment. For more information, see the Datastore mode Python API reference documentation.

# 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(f"Saved {task.key.name}: {task['description']}")

Ruby

Before trying this sample, follow the Ruby setup instructions in Setting Up a Ruby Development Environment. For more information, see the Datastore mode Ruby API reference documentation.

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

# Instantiate a client
datastore = Google::Cloud::Datastore.new

# The kind for the new entity
kind = "Task"
# The name/ID for the new entity
# task_name = "sampleTask"
# The Cloud Datastore key for the new entity
task_key = datastore.key kind, task_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']}"
task_key = datastore.find task_key

Additional resources

Dependency on App Engine application

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

Google App Engine Standard Environment Client Libraries

Integrate Firestore in Datastore mode 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 2 Google Datastore NDB Client Library
Python 3 Google Cloud Datastore 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