Entities, Properties, and Keys

Data objects in Google Cloud Datastore are known as entities. An entity has one or more named properties, each of which can have one or more values. Entities of the same kind do not need to have the same properties, and an entity's values for a given property do not all need to be of the same data type. (If necessary, an application can establish and enforce such restrictions in its own data model.)

Cloud Datastore supports a variety of data types for property values. These include, among others:

  • Integers
  • Floating-point numbers
  • Strings
  • Dates
  • Binary data

Each entity in Cloud Datastore has a key that uniquely identifies it. The key consists of the following components:

  • The namespace of the entity, which allows for multitenancy
  • The kind of the entity, which categorizes it for the purpose of Cloud Datastore queries
  • An identifier for the individual entity, which can be either
    • a key name string
    • an integer numeric ID
  • An optional ancestor path locating the entity within the Cloud Datastore hierarchy

An application can fetch an individual entity from Cloud Datastore using the entity's key, or it can retrieve one or more entities by issuing a query based on the entities' keys or property values.

Cloud Datastore itself does not enforce any restrictions on the structure of entities, such as whether a given property has a value of a particular type; this task is left to the application.

The snippets on this page build upon the example at Getting started with Google Cloud Datastore.

Working with entities

Applications can use the Cloud Datastore API to create, retrieve, update, and delete entities. If the application knows the complete key for an entity (or can derive it from its parent key, kind, and identifier), it can use the key to operate directly on the entity. An application can also obtain an entity's key as a result of a Cloud Datastore query; see the Cloud Datastore Queries topic for more information.

Creating an entity

You create a new entity by initializing it and setting its properties:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Entity task = new Entity()
{
    Key = _db.CreateKeyFactory("Task").CreateKey("sampleTask"),
    ["category"] = "Personal",
    ["done"] = false,
    ["priority"] = 4,
    ["description"] = "Learn Cloud Datastore"
};

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

type Task struct {
	Category        string
	Done            bool
	Priority        float64
	Description     string `datastore:",noindex"`
	PercentComplete float64
	Created         time.Time
}
task := &Task{
	Category:        "Personal",
	Done:            false,
	Priority:        4,
	Description:     "Learn Cloud Datastore",
	PercentComplete: 10.0,
	Created:         time.Now(),
}

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Entity task = Entity.newBuilder(taskKey)
    .set("category", "Personal")
    .set("done", false)
    .set("priority", 4)
    .set("description", "Learn Cloud Datastore")
    .build();

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const task = {
  category: 'Personal',
  done: false,
  priority: 4,
  description: 'Learn Cloud Datastore'
};

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$task = $datastore->entity('Task', [
    'category' => 'Personal',
    'done' => false,
    'priority' => 4,
    'description' => 'Learn Cloud Datastore'
]);

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task = datastore.Entity(client.key('Task'))
task.update({
    'category': 'Personal',
    'done': False,
    'priority': 4,
    'description': 'Learn Cloud Datastore'
})

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task = datastore.entity "Task" do |t|
  t["category"] = "Personal"
  t["done"] = false
  t["priority"] = 4
  t["description"] = "Learn Cloud Datastore"
end

You can save the entity to Cloud Datastore using upsert (which will overwrite an entity if it already exists in Cloud Datastore) or insert (which requires that the entity key not already exist in Cloud Datastore).

Here's how you upsert an entity:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

_db.Upsert(_sampleTask);

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

key, err := client.Put(ctx, key, task)

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Entity task = Entity.newBuilder(keyFactory.newKey("sampleTask")).build();
datastore.put(task);

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const entity = {
  key: taskKey,
  data: task
};

datastore.upsert(entity)
  .then(() => {
    // Task inserted successfully.
  });

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$key = $datastore->key('Task', 'sampleTask');
$task = $datastore->entity($key, [
    'category' => 'Personal',
    'done' => false,
    'priority' => 4,
    'description' => 'Learn Cloud Datastore'
]);
$datastore->upsert($task);

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

complete_key = client.key('Task', 'sample_task')

task = datastore.Entity(key=complete_key)

task.update({
    'category': 'Personal',
    'done': False,
    'priority': 4,
    'description': 'Learn Cloud Datastore'
})

client.put(task)

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task = datastore.entity "Task", "sampleTask" do |t|
  t["category"] = "Personal"
  t["done"] = false
  t["priority"] = 4
  t["description"] = "Learn Cloud Datastore"
end
datastore.save task

Here's how you insert an entity:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Entity task = new Entity()
{
    Key = _keyFactory.CreateIncompleteKey()
};
task.Key = _db.Insert(task);

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

_, err := client.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
	// We first check that there is no entity stored with the given key.
	var empty Task
	if err := tx.Get(taskKey, &empty); err != datastore.ErrNoSuchEntity {
		return err
	}
	// If there was no matching entity, store it now.
	_, err := tx.Put(taskKey, &task)
	return err
})

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Key taskKey = datastore.add(FullEntity.newBuilder(keyFactory.newKey()).build()).getKey();

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const entity = {
  key: taskKey,
  data: task
};

datastore.insert(entity)
  .then(() => {
    // Task inserted successfully.
  });

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$task = $datastore->entity('Task', [
    'category' => 'Personal',
    'done' => false,
    'priority' => 4,
    'description' => 'Learn Cloud Datastore'
]);
$datastore->insert($task);

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

with client.transaction():
    incomplete_key = client.key('Task')

    task = datastore.Entity(key=incomplete_key)

    task.update({
        'category': 'Personal',
        'done': False,
        'priority': 4,
        'description': 'Learn Cloud Datastore'
    })

    client.put(task)

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

datastore.transaction do |tx|
  task = datastore.entity "Task" do |t|
    t["category"] = "Personal"
    t["done"] = false
    t["priority"] = 4
    t["description"] = "Learn Cloud Datastore"
  end
  datastore.save task
end

Retrieving an entity

To retrieve an entity from Cloud Datastore, use its key for a lookup:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Entity task = _db.Lookup(_sampleTask.Key);

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

var task Task
err := client.Get(ctx, taskKey, &task)

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Entity task = datastore.get(taskKey);

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

datastore.get(taskKey)
  .then((results) => {
    // Task found.
    const entity = results[0];

    // entity = {
    //   category: 'Personal',
    //   done: false,
    //   priority: 4,
    //   description: 'Learn Cloud Datastore'
    // };
    console.log(entity);
  });

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$key = $datastore->key('Task', 'sampleTask');
$task = $datastore->lookup($key);

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

key = client.key('Task', 'sample_task')
task = client.get(key)

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task_key = datastore.key "Task", "sampleTask"
task = datastore.find task_key

Updating an entity

To update an existing entity, modify the properties of the entity and store it using the key:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

_sampleTask["priority"] = 5;
_db.Update(_sampleTask);

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

tx, err := client.NewTransaction(ctx)
if err != nil {
	log.Fatalf("client.NewTransaction: %v", err)
}
var task Task
if err := tx.Get(taskKey, &task); err != nil {
	log.Fatalf("tx.Get: %v", err)
}
task.Priority = 5
if _, err := tx.Put(taskKey, task); err != nil {
	log.Fatalf("tx.Put: %v", err)
}
if _, err := tx.Commit(); err != nil {
	log.Fatalf("tx.Commit: %v", err)
}

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Entity task = Entity.newBuilder(datastore.get(taskKey)).set("priority", 5).build();
datastore.update(task);

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const entity = {
  key: taskKey,
  data: task
};

datastore.update(entity)
  .then(() => {
    // Task updated successfully.
  });

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$transaction = $datastore->transaction();
$key = $datastore->key('Task', 'sampleTask');
$task = $transaction->lookup($key);
$task['priority'] = 5;
$transaction->upsert($task);
$transaction->commit();

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

with client.transaction():
    key = client.key('Task', 'sample_task')
    task = client.get(key)

    task['done'] = True

    client.put(task)

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

datastore.transaction do |tx|
  task = datastore.find "Task", "sampleTask"
  task["priority"] = 5
  datastore.save task
end

The object data overwrites the existing entity. The entire object is sent to Cloud Datastore. If the entity does not exist, the update will fail. If you want to update-or-create an entity, use upsert as described previously.

Deleting an entity

Given an entity's key, you can delete the entity:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

_db.Delete(_sampleTask.Key);

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

err := client.Delete(ctx, key)

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

datastore.delete(taskKey);

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

datastore.delete(taskKey)
  .then(() => {
    // Task deleted successfully.
  });

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$datastore->delete($taskKey);

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

key = client.key('Task', 'sample_task')
client.delete(key)

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task_key = datastore.key "Task", "sampleTask"
datastore.delete task_key

Batch operations

Cloud Datastore supports batch versions of the operations which allow it to operate on multiple objects in a single Cloud Datastore call.

Such batch calls are faster than making separate calls for each individual entity because they incur the overhead for only one service call. If multiple entity groups are involved, the work for all the groups is performed in parallel on the server side.

For example, you can upsert multiple entities:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

var taskList = new[]
{
    new Entity()
    {
        Key = _keyFactory.CreateIncompleteKey(),
        ["category"] = "Personal",
        ["done"] = false,
        ["priority"] = 4,
        ["description"] = "Learn Cloud Datastore"
    },
    new Entity()
    {
        Key = _keyFactory.CreateIncompleteKey(),
        ["category"] = "Personal",
        ["done"] = "false",
        ["priority"] = 5,
        ["description"] = "Integrate Cloud Datastore"
    }
};
var keyList = _db.Upsert(taskList[0], taskList[1]);

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

tasks := []*Task{
	{
		Category:    "Personal",
		Done:        false,
		Priority:    4,
		Description: "Learn Cloud Datastore",
	},
	{
		Category:    "Personal",
		Done:        false,
		Priority:    5,
		Description: "Integrate Cloud Datastore",
	},
}
keys := []*datastore.Key{
	datastore.IncompleteKey("Task", nil),
	datastore.IncompleteKey("Task", nil),
}

keys, err := client.PutMulti(ctx, keys, tasks)

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

FullEntity<IncompleteKey> task1 = FullEntity.newBuilder(keyFactory.newKey())
    .set("category", "Personal")
    .set("done", false)
    .set("priority", 4)
    .set("description", "Learn Cloud Datastore")
    .build();
FullEntity<IncompleteKey> task2 = Entity.newBuilder(keyFactory.newKey())
    .set("category", "Personal")
    .set("done", false)
    .set("priority", 5)
    .set("description", "Integrate Cloud Datastore")
    .build();
List<Entity> tasks = datastore.add(task1, task2);
Key taskKey1 = tasks.get(0).getKey();
Key taskKey2 = tasks.get(1).getKey();

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const entities = [
  {
    key: taskKey1,
    data: task1
  },
  {
    key: taskKey2,
    data: task2
  }
];

datastore.upsert(entities)
  .then(() => {
    // Tasks inserted successfully.
  });

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$datastore->upsertBatch($tasks);

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

client.put_multi([task1, task2])

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task1 = datastore.entity "Task" do |t|
  t["category"] = "Personal"
  t["done"] = false
  t["priority"] = 4
  t["description"] = "Learn Cloud Datastore"
end

task2 = datastore.entity "Task" do |t|
  t["category"] = "Personal"
  t["done"] = false
  t["priority"] = 5
  t["description"] = "Integrate Cloud Datastore"
end

tasks = datastore.save(task1, task2)
task_key1 = tasks[0].key
task_key2 = tasks[1].key

You can lookup multiple entities:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

var keys = new Key[] { _keyFactory.CreateKey(1), _keyFactory.CreateKey(2) };
var tasks = _db.Lookup(keys[0], keys[1]);

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

var tasks []*Task
err := client.GetMulti(ctx, taskKeys, &tasks)

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Iterator<Entity> tasks = datastore.get(taskKey1, taskKey2);

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const keys = [taskKey1, taskKey2];

datastore.get(keys)
  .then((results) => {
    // Tasks retrieved successfully.
    const tasks = results[0];

    console.log(tasks);
  });

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$result = $datastore->lookupBatch($keys);
if (isset($result['found'])) {
    // $result['found'] is an array of entities.
} else {
    // No entities found.
}

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

tasks = client.get_multi(keys)

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task_key1 = datastore.key "Task", "sampleTask1"
task_key2 = datastore.key "Task", "sampleTask2"
tasks = datastore.find_all task_key1, task_key2

You can delete multiple entities:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

var keys = new Key[] { _keyFactory.CreateKey(1), _keyFactory.CreateKey(2) };
_db.Delete(keys);

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

err := client.DeleteMulti(ctx, taskKeys)

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

datastore.delete(taskKey1, taskKey2);

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const keys = [taskKey1, taskKey2];

datastore.delete(keys)
  .then(() => {
    // Tasks deleted successfully.
  });

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$datastore->deleteBatch($keys);

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

client.delete_multi(keys)

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task_key1 = datastore.key "Task", "sampleTask1"
task_key2 = datastore.key "Task", "sampleTask2"
datastore.delete task_key1, task_key2

Batch operations do not change your read, write, or delete costs, which are documented at Pricing and Quota. You will be charged for every key in a batched operation, whether or not each key exists.

The size of the entities involved in an operation does not affect the read, write, or delete costs. However, the size of entities does impact your storage size costs.

Kinds and identifiers

Each Cloud Datastore entity is of a particular kind, which categorizes the entity for the purpose of queries: for instance, a task list application might represent each task to complete with an entity of kind Task.

All kind names that begin with two underscores (__) are reserved and may not be used.

Assigning identifiers

In addition to a kind, each entity has an identifier, assigned when the entity is created. Because it is part of the entity's key, the identifier is associated permanently with the entity and cannot be changed. It can be assigned in either of two ways:

  • Your application can specify its own key name string for the entity.
  • You can have Cloud Datastore automatically assign the entity an integer numeric ID.

The following example creates a key with kind Task using a key name, "sampleTask", as the identifier:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Key key = _db.CreateKeyFactory("Task").CreateKey("sampleTask");

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

taskKey := datastore.NameKey("Task", "sampletask", nil)

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Key taskKey = datastore.newKeyFactory().setKind("Task").newKey("sampleTask");

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const taskKey = datastore.key([
  'Task',
  'sampleTask'
]);

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$taskKey = $datastore->key('Task', 'sampleTask');

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

key = client.key('Task', 'sample_task')

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task_key = datastore.key "Task", "sampleTask"

Cloud Datastore can also automatically assign IDs. Cloud Datastore generates a random sequence of unused IDs that are approximately uniformly distributed. Each ID can be up to 16 decimal digits long.

The following example creates a key with kind Task, without using a key name. The full key (including the automatically assigned ID) of the entity will be returned when an entity with the incomplete key is saved to Cloud Datastore:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Key incompleteKey = _db.CreateKeyFactory("Task").CreateIncompleteKey();
Key key = _db.AllocateId(incompleteKey);

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

taskKey := datastore.IncompleteKey("Task", nil)

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

KeyFactory keyFactory = datastore.newKeyFactory().setKind("Task");
Key taskKey = datastore.allocateId(keyFactory.newKey());

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const taskKey = datastore.key('Task');

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$taskKey = $datastore->key('Task');

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

key = client.key('Task')

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task_key = datastore.key "Task"

If you want to display the entity IDs to the user, and/or depend upon their order, the best thing to do is use manual allocation.

Ancestor paths

Entities in Cloud Datastore form a hierarchically structured space similar to the directory structure of a file system. When you create an entity, you can optionally designate another entity as its parent; the new entity is a child of the parent entity (note that unlike in a file system, the parent entity need not actually exist). An entity without a parent is a root entity. The association between an entity and its parent is permanent, and cannot be changed once the entity is created. Cloud Datastore will never assign the same numeric ID to two entities with the same parent, or to two root entities (those without a parent).

An entity's parent, parent's parent, and so on recursively, are its ancestors; its children, children's children, and so on, are its descendants. The sequence of entities beginning with a root entity and proceeding from parent to child, leading to a given entity, constitute that entity's ancestor path. The complete key identifying the entity consists of a sequence of kind-identifier pairs specifying its ancestor path and terminating with those of the entity itself:

[User:alice, TaskList:default, Task:sampleTask]

For a root entity, the ancestor path is empty and the key consists solely of the entity's own kind and identifier:

[User:alice]

Levels of parents

Use levels of parents to organize your data. For example, if your application organizes Task entities by TaskList entities, use one level of parent:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Key rootKey = _db.CreateKeyFactory("TaskList").CreateKey("default");
Key key = new KeyFactory(rootKey, "Task").CreateKey("sampleTask");

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

parentKey := datastore.NameKey("TaskList", "default", nil)
taskKey := datastore.NameKey("Task", "sampleTask", parentKey)

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Key taskKey = datastore.newKeyFactory()
    .addAncestors(PathElement.of("TaskList", "default"))
    .setKind("Task")
    .newKey("sampleTask");

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const taskKey = datastore.key([
  'TaskList',
  'default',
  'Task',
  'sampleTask'
]);

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$taskKey = $datastore->key('TaskList', 'default')
    ->pathElement('Task', 'sampleTask');

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

key = client.key('TaskList', 'default', 'Task', 'sample_task')
# Alternatively
parent_key = client.key('TaskList', 'default')
key = client.key('Task', 'sample_task', parent=parent_key)

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task_key = datastore.key [["TaskList", "default"], ["Task", "sampleTask"]]

If your application organizes Task entities first by User entities and then by TaskList entities, use multiple levels of parents:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Key rootKey = _db.CreateKeyFactory("User").CreateKey("Alice");
Key taskListKey = new KeyFactory(rootKey, "TaskList").CreateKey("default");
Key key = new KeyFactory(taskListKey, "Task").CreateKey("sampleTask");

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

userKey := datastore.NameKey("User", "alice", nil)
parentKey := datastore.NameKey("TaskList", "default", userKey)
taskKey := datastore.NameKey("Task", "sampleTask", parentKey)

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

KeyFactory keyFactory = datastore.newKeyFactory()
    .addAncestors(PathElement.of("User", "Alice"), PathElement.of("TaskList", "default"))
    .setKind("Task");
Key taskKey = keyFactory.newKey("sampleTask");

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const taskKey = datastore.key([
  'User',
  'alice',
  'TaskList',
  'default',
  'Task',
  'sampleTask'
]);

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$taskKey = $datastore->key('User', 'alice')
    ->pathElement('TaskList', 'default')
    ->pathElement('Task', 'sampleTask');

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

key = client.key(
    'User', 'alice',
    'TaskList', 'default',
    'Task', 'sample_task')

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task_key = datastore.key([
                           ["User", "alice"],
                           ["TaskList", "default"],
                           ["Task", "sampleTask"]
                         ])

As shown in the example above, when you create an entity with a parent, you specify the parent's complete ancestor path.

An application that maintains user profiles may require only one level of parent for the user profile data. For example, use a single level User ancestor path for Profile entities:

[User:alice, Profile:public]

An application that provides conference room scheduling may require multiple levels of parents, such as a multiple level Building/Floor ancestor path for Room entities:

[Building:C, Floor:1, Room:123]

Entity groups

An entity group consists of a root entity and all of its descendants. Applications typically use entity groups to organize highly related data. For example, an application could use an entity group to store data about one product, or one user profile. For information about consistency levels and performance considerations when you use entity groups, see Transactions and entity groups.

System-allocated ID values are guaranteed unique to the entity group. If you copy an entity from one entity group or namespace to another and wish to preserve the ID part of the key, be sure to allocate the ID first to prevent Datastore from selecting that ID for a future assignment.

Properties and value types

The data values associated with an entity consist of one or more properties. Each property has a name and one or more values.

A property can have values of more than one type, and two entities can have values of different types for the same property. A property can be indexed or unindexed (queries that order or filter on a property p will ignore entities where p is unindexed).

Some example properties:

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Entity task = new Entity()
{
    Key = _db.CreateKeyFactory("Task").CreateKey("sampleTask"),
    ["category"] = "Personal",
    ["created"] = new DateTime(1999, 01, 01, 0, 0, 0, DateTimeKind.Utc),
    ["done"] = false,
    ["priority"] = 4,
    ["percent_complete"] = 10.0,
    ["description"] = new Value()
    {
        StringValue = "Learn Cloud Datastore",
        ExcludeFromIndexes = true
    },
};

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

type Task struct {
	Category        string
	Done            bool
	Priority        int
	Description     string `datastore:",noindex"`
	PercentComplete float64
	Created         time.Time
}
task := &Task{
	Category:        "Personal",
	Done:            false,
	Priority:        4,
	Description:     "Learn Cloud Datastore",
	PercentComplete: 10.0,
	Created:         time.Now(),
}

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Entity task = Entity.newBuilder(taskKey)
    .set("category", "Personal")
    .set("created", DateTime.now())
    .set("done", false)
    .set("priority", 4)
    .set("percent_complete", 10.0)
    .set("description",
      StringValue.newBuilder("Learn Cloud Datastore").setExcludeFromIndexes(true).build())
    .build();

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const task = [
  {
    name: 'category',
    value: 'Personal'
  },
  {
    name: 'created',
    value: new Date()
  },
  {
    name: 'done',
    value: false
  },
  {
    name: 'priority',
    value: 4
  },
  {
    name: 'percent_complete',
    value: 10.0
  },
  {
    name: 'description',
    value: 'Learn Cloud Datastore',
    excludeFromIndexes: true
  }
];

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$task = $datastore->entity(
    $key,
    [
        'category' => 'Personal',
        'created' => new DateTime(),
        'done' => false,
        'priority' => 4,
        'percent_complete' => 10.0,
        'description' => 'Learn Cloud Datastore'
    ],
    ['excludeFromIndexes' => ['description']]
);

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task = datastore.Entity(
    key,
    exclude_from_indexes=['description'])
task.update({
    'category': 'Personal',
    'description': 'Learn Cloud Datastore',
    'created': datetime.datetime.utcnow(),
    'done': False,
    'priority': 4,
    'percent_complete': 10.5,
})

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task = datastore.entity "Task" do |t|
  t["category"] = "Personal"
  t["created"] = Time.now
  t["done"] = false
  t["priority"] = 4
  t["percent_complete"] = 10.0
  t["description"] = "Learn Cloud Datastore"
  t.exclude_from_indexes! "description", true
end

A property with more than one value is called an array property. This example contains two array properties. The first is named tags with values fun and programming. The second is named collaborators with values alice and bob.

C#

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Entity task = new Entity()
{
    Key = _db.CreateKeyFactory("Task").CreateKey("sampleTask"),
    ["collaborators"] = new ArrayValue() { Values = { "alice", "bob" } },
    ["tags"] = new ArrayValue() { Values = { "fun", "programming" } }
};

Go

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

type Task struct {
	Tags          []string
	Collaborators []string
}
task := &Task{
	Tags:          []string{"fun", "programming"},
	Collaborators: []string{"alice", "bob"},
}

Java

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

Entity task = Entity.newBuilder(taskKey)
    .set("tags", "fun", "programming")
    .set("collaborators", "alice", "bob")
    .build();

Node.js

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

const task = {
  tags: [
    'fun',
    'programming'
  ],
  collaborators: [
    'alice',
    'bob'
  ]
};

PHP

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

$task = $datastore->entity(
    $key,
    [
        'tags' => ['fun', 'programming'],
        'collaborators' => ['alice', 'bob']
    ]
);

Python

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task = datastore.Entity(key)
task.update({
    'tags': [
        'fun',
        'programming'
    ],
    'collaborators': [
        'alice',
        'bob'
    ]
})

Ruby

For more on installing and creating a Cloud Datastore client, refer to Cloud Datastore Client Libraries.

task = datastore.entity "Task", "sampleTask" do |t|
  t["tags"] = ["fun", "programming"]
  t["collaborators"] = ["alice", "bob"]
end

In JSON, an array property can be assigned by using the arrayValue field, which is of type ArrayValue, and setting its values field to an array of values. For a property to be unindexed, the excludeFromIndexes field of the property's value object must be set to true.

In protocol buffers, an array property can be assigned by using the array_value field, which is of type ArrayValue, and populating its values field with multiple Value objects. For a property to be unindexed, the exclude_from_indexes field of Value must be set to true.

Properties are stored as a string/value map that contains the entity's property names and values. The following types are supported for values:

Array

  • JSON
    • field name: arrayValue
    • type: an ArrayValue object that contains an array of JSON Value objects
  • Protocol buffer
    • field name: array_value
    • type: an ArrayValue message that contains one or more Value messages
  • Sort order: None
  • Notes: Cannot contain another array value. The value instance must not set meaning or exclude_from_indexes.

Boolean

  • JSON
    • field name: booleanValue
    • type: true or false
  • Protocol buffer
    • field name: boolean_value
    • type: bool
  • Sort order: false<true

Blob

  • JSON
    • field name: blobValue
    • type: string. Must be base64-encoded.
  • Protocol buffer
    • field name: blob_value
    • type: bytes
  • Sort order: Byte order
  • Notes: Up to 1,500 bytes if property is indexed, up to 1,048,487 bytes (1 MiB - 89 bytes) otherwise.

Date and time

  • JSON
    • field name: timestampValue
    • type: string (RFC 3339 formatted, with milliseconds, for instance 2013-05-14T00:01:00.234Z)
  • Protocol buffer
    • field name: timestamp_value
    • type: Timestamp
  • Sort order: Chronological
  • Notes: When stored in Cloud Datastore, precise only to microseconds; any additional precision is rounded down.

Embedded entity

  • JSON
    • field name: entityValue
    • type: a JSON entity
  • Protocol buffer
    • field name: entity_value
    • type: an Entity message
  • Sort order: None
  • Notes: When indexed, you can query on subproperties. If you exclude this value from indexing, then all subproperties are also excluded from indexing.

Floating-point number

  • JSON
    • field name: doubleValue
    • type: number
  • Protocol buffer
    • field name: double_value
    • type: double
  • Sort order: Numeric
  • Notes: 64-bit double precision, IEEE 754

Geographical point

  • JSON
    • field name: geoPointValue
    • type: a JSON latitude/longitude pair
  • Protocol buffer
    • field name: geo_point_value
    • type: a LatLng message
  • Sort order: By latitude, then longitude

Integer

  • JSON
    • field name: integerValue
    • type: number or string. Use strings for integers that cannot be exactly represented as numbers.
  • Protocol buffer
    • field name: integer_value
    • type: int64
  • Sort order: Numeric

Key

  • JSON
    • field name: keyValue
    • type: a JSON Cloud Datastore key
  • Protocol buffer
    • field name: key_value
    • type: a Key message
  • Sort order: By path elements (kind, identifier, kind, identifier...)

Null

  • JSON
    • field name: nullValue
    • type: null
  • Protocol buffer
    • field name: null_value
    • type: NullValue
  • Sort order: None

Text string

  • JSON
    • field name: stringValue
    • type: string
  • Protocol buffer
    • field name: string_value
    • type: string
  • Sort order: UTF-8 encoded byte order
  • Notes: Up to 1,500 bytes if property is indexed, up to 1,048,487 bytes (1 MiB - 89 bytes) otherwise.

Value type ordering

When a query involves a property with values of mixed types, Cloud Datastore uses a deterministic ordering based on the internal representations. The following list shows the order:

  1. Null values
  2. Fixed-point numbers
    • Integers
    • Dates and times
  3. Boolean values
  4. Byte strings
  5. Unicode strings
  6. Floating-point numbers
  7. Geographical points
  8. Cloud Datastore keys

Send feedback about...

Cloud Datastore Documentation