Datastore mode Client Libraries

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

For more information, see Setting Up a C# Development Environment.
Install-Package Google.Cloud.Datastore.V1

Go

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

Java

For more information, see Setting Up a Java Development Environment. Si usas Maven, agrega lo siguiente a tu archivo pom.xml:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-datastore</artifactId>
  <version>1.61.0</version>
</dependency>
Si usas Gradle, agrega lo siguiente a tus dependencias:
compile 'com.google.cloud:google-cloud-datastore:1.61.0'
Si usas SBT, agrega lo siguiente a tus dependencias:
libraryDependencies += "com.google.cloud" % "google-cloud-datastore" % "1.61.0"

Si usas IntelliJ o Eclipse, puedes agregar bibliotecas cliente a tu proyecto mediante los siguientes complementos IDE:

Los complementos brindan funcionalidades adicionales, como administración de claves para las cuentas de servicio. Consulta la documentación de cada complemento para obtener más detalles.

Node.js

For more information, see Setting Up a Node.js Development Environment.
npm install --save @google-cloud/datastore

PHP

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 more information, see the GCP authentication documentation .

GCP Console

  1. En GCP Console, ve a la página Crear clave de la cuenta de servicio.

    Ir a la página Crear clave de la cuenta de servicio
  2. Desde la lista desplegable de la Cuenta de servicio, selecciona Nueva cuenta de servicio.
  3. En el campo Nombre de cuenta de servicio, ingresa un nombre.
  4. En la lista desplegable Función, selecciona Proyecto > Propietario.

    Nota: El campo Función autoriza tu cuenta de servicio para acceder a los recursos. Puedes ver y cambiar este campo luego con GCP Console. Si desarrollas una aplicación de producción, especifica permisos más detallados que Proyecto > Propietario. Para obtener más información, consulta Cómo otorgar funciones a las cuentas de servicio.
  5. Haz clic en Crear. Se descargará un archivo JSON a tu computadora que contiene tus descargas de claves.

Línea de comandos

Puedes ejecutar los siguientes comandos con el SDK de Cloud en tu máquina local o dentro de Cloud Shell.

  1. Crea la cuenta de servicio. Reemplaza [NAME] con el nombre que le quieres poner a la cuenta de servicio.

    gcloud iam service-accounts create [NAME]
  2. Otorga permisos a la cuenta de servicio. Reemplaza [PROJECT_ID] con el ID del proyecto.

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    Nota: El campo Función autoriza a tu cuenta de servicio para acceder a los recursos. Puedes ver y cambiar este campo luego con GCP Console. Si desarrollas una aplicación de producción, especifica permisos más detallados que Proyecto > Propietario. Para obtener más información, consulta Cómo otorgar funciones a las cuentas de servicio.
  3. Genera el archivo de claves. Reemplaza [FILE_NAME] con un nombre para el archivo de claves.

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

Proporciónale las credenciales de autenticación a tu código de la aplicación mediante la configuración de la variable de entorno GOOGLE_APPLICATION_CREDENTIALS. Reemplaza [PATH] con la ruta de acceso al archivo JSON que contiene la clave de tu cuenta de servicio y [FILE_NAME] con el nombre del archivo. Esta variable solo se aplica a la sesión actual de shell. Por lo tanto, si abres una sesión nueva, deberás volver a configurar la variable.

Linux o macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Por ejemplo:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

Con PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Por ejemplo:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

Con el símbolo del sistema:

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');

async function quickStart() {
  // Your Google Cloud Platform project ID
  const projectId = 'YOUR_PROJECT_ID';

  // Creates a client
  const datastore = new 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
  await datastore.save(task);
  console.log(`Saved ${task.key.name}: ${task.data.description}`);
}
quickStart().catch(console.error);

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('Saved {}: {}'.format(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"

# 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']}"

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

¿Te sirvió esta página? Envíanos tu opinión:

Enviar comentarios sobre…

Cloud Datastore Documentation