Datastore Queries

A query retrieves entities from Firestore in Datastore mode that meet a specified set of conditions.

The query operates on entities of a given kind; it can specify filters on the entities' property values, keys, and ancestors, and can return zero or more entities as results. A query can also specify sort orders to sequence the results by their property values. The results include all entities that have at least one value for every property named in the filters and sort orders, and whose property values meet all the specified filter criteria. The query can return entire entities, projected entities, or just entity keys.

A typical query includes the following:

  • An entity kind to which the query applies
  • Zero or more filters based on the entities' property values, keys, and ancestors
  • Zero or more sort orders to sequence the results

When executed, the query retrieves all entities of the given kind that satisfy all of the given filters, sorted in the specified order. Queries execute as read-only.

Note: To conserve memory and improve performance, a query should, whenever possible, specify a limit on the number of results returned.

Every query computes its results using one or more indexes, which contain entity keys in a sequence specified by the index's properties and, optionally, the entity's ancestors. The indexes are updated incrementally to reflect any changes the application makes to its entities, so that the correct results of all queries are available with no further computation needed.

The index-based query mechanism supports a wide range of queries and is suitable for most applications. However, it does not support some kinds of query common in other database technologies: in particular, joins and aggregate queries aren't supported within the Datastore mode query engine. See Restrictions on queries, below, for limitations on Datastore mode queries.

Query interface

Here's a basic example of issuing a query against a Datastore mode database. It retrieves all tasks that are not yet done with priorities greater than or equal to 4, sorted in descending order by priority:

C#

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore C# API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query query = new Query("Task")
{
    Filter = Filter.And(Filter.Equal("done", false),
        Filter.GreaterThanOrEqual("priority", 4)),
    Order = { { "priority", PropertyOrder.Types.Direction.Descending } }
};

Go

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Go API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query := datastore.NewQuery("Task").
	FilterField("Done", "=", false).
	FilterField("Priority", ">=", 4).
	Order("-Priority")

Java

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Java API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query<Entity> query =
    Query.newEntityQueryBuilder()
        .setKind("Task")
        .setFilter(
            CompositeFilter.and(
                PropertyFilter.eq("done", false), PropertyFilter.ge("priority", 4)))
        .setOrderBy(OrderBy.desc("priority"))
        .build();

Node.js

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Node.js API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const query = datastore
  .createQuery('Task')
  .filter('done', '=', false)
  .filter('priority', '>=', 4)
  .order('priority', {
    descending: true,
  });

PHP

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore PHP API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

$query = $datastore->query()
    ->kind('Task')
    ->filter('done', '=', false)
    ->filter('priority', '>=', 4)
    ->order('priority', Query::ORDER_DESCENDING);

Python

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Python API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import datastore

# For help authenticating your client, visit
# https://cloud.google.com/docs/authentication/getting-started
client = datastore.Client()

query = client.query(kind="Task")
query.add_filter("done", "=", False)
query.add_filter("priority", ">=", 4)
query.order = ["-priority"]

Ruby

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Ruby API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query = datastore.query("Task")
                 .where("done", "=", false)
                 .where("priority", ">=", 4)
                 .order("priority", :desc)

GQL


SELECT * FROM Task
WHERE done = FALSE AND priority >= 4
ORDER BY priority DESC

Here's how to run a query:

C#

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore C# API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query query = new Query("Task");
DatastoreQueryResults tasks = _db.RunQuery(query);

Go

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Go API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

it := client.Run(ctx, query)
for {
	var task Task
	_, err := it.Next(&task)
	if err == iterator.Done {
		break
	}
	if err != nil {
		log.Fatalf("Error fetching next task: %v", err)
	}
	fmt.Printf("Task %q, Priority %d\n", task.Description, task.Priority)
}

Java

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Java API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

QueryResults<Entity> tasks = datastore.run(query);

Node.js

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Node.js API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const [tasks] = await datastore.runQuery(query);
console.log('Tasks:');
tasks.forEach(task => console.log(task));

PHP

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore PHP API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

$result = $datastore->runQuery($query);

Python

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Python API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import datastore

# For help authenticating your client, visit
# https://cloud.google.com/docs/authentication/getting-started
client = datastore.Client()

query = client.query()
results = list(query.fetch())

Ruby

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Ruby API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

tasks = datastore.run query

GQL

Not Applicable

Query structure

A query can specify an entity kind, zero or more filters, and zero or more sort orders.

Filters

A query's filters set constraints on the properties, keys, and ancestors of the entities to be retrieved.

Property filters

A property filter specifies

  • A property name
  • A comparison operator
  • A property value

This example returns Task entities that are marked not done:

C#

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore C# API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query query = new Query("Task")
{
    Filter = Filter.Equal("done", false)
};

Go

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Go API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query := datastore.NewQuery("Task").FilterField("Done", "=", false)

Java

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Java API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query<Entity> query =
    Query.newEntityQueryBuilder()
        .setKind("Task")
        .setFilter(PropertyFilter.eq("done", false))
        .build();

Node.js

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Node.js API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const query = datastore.createQuery('Task').filter('done', '=', false);

PHP

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore PHP API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

$query = $datastore->query()
    ->kind('Task')
    ->filter('done', '=', false);

Python

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Python API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import datastore

# For help authenticating your client, visit
# https://cloud.google.com/docs/authentication/getting-started
client = datastore.Client()

query = client.query(kind="Task")
query.add_filter("done", "=", False)

Ruby

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Ruby API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query = datastore.query("Task")
                 .where("done", "=", false)

GQL


SELECT * FROM Task WHERE done = FALSE

The property value must be supplied by the application; it cannot refer to or be calculated in terms of other properties. An entity satisfies the filter if it has a property of the given name whose value compares to the value specified in the filter in the manner described by the comparison operator. If the property of the given name is array-valued, the entity satisfies the filter if any of the values compares to the value specified in the filter in the manner described by the comparison operator.

The comparison operator can be any of the following:

Operator Meaning
EQUAL Equal to
LESS_THAN Less than
LESS_THAN_OR_EQUAL Less than or equal to
GREATER_THAN Greater than
GREATER_THAN_OR_EQUAL Greater than or equal to
NOT_EQUAL Not equal to
IN Member of the specified list. Equal to any of the values in a specified list.
NOT_IN Not a member of the specified list. Not equal to any of the values in a specified list.

Composite filters

A composite filter consists of more than one property filter. You can combine filters with AND and OR. This example returns Task entities that are marked not done and have a priority of 4:

C#

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore C# API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query query = new Query("Task")
{
    Filter = Filter.And(Filter.Equal("done", false),
        Filter.Equal("priority", 4)),
};

Go

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Go API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query := datastore.NewQuery("Task").
	FilterField("Done", "=", false).
	FilterField("Priority", "=", 4)

Java

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Java API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query<Entity> query =
    Query.newEntityQueryBuilder()
        .setKind("Task")
        .setFilter(
            CompositeFilter.and(
                PropertyFilter.eq("done", false), PropertyFilter.eq("priority", 4)))
        .build();

Node.js

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Node.js API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const query = datastore
  .createQuery('Task')
  .filter('done', '=', false)
  .filter('priority', '=', 4);

PHP

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore PHP API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

$query = $datastore->query()
    ->kind('Task')
    ->filter('done', '=', false)
    ->filter('priority', '=', 4);

Python

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Python API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import datastore

# For help authenticating your client, visit
# https://cloud.google.com/docs/authentication/getting-started
client = datastore.Client()

query = client.query(kind="Task")
query.add_filter("done", "=", False)
query.add_filter("priority", "=", 4)

Ruby

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Ruby API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query = datastore.query("Task")
                 .where("done", "=", false)
                 .where("priority", "=", 4)

GQL


SELECT * FROM Task WHERE done = FALSE AND priority = 4

This examples combines filters with a logical OR:

C#

Snippet not available.

Go

Snippet not available.

Java

To learn how to install and use the client library for Datastore mode, see Datastore mode client libraries. For more information, see the Datastore mode Java API reference documentation.

To authenticate to Datastore mode, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.QueryResults;
import com.google.cloud.datastore.StructuredQuery.CompositeFilter;
import com.google.cloud.datastore.StructuredQuery.Filter;
import com.google.cloud.datastore.StructuredQuery.PropertyFilter;

public class OrFilterQuery {
  public static void invoke() throws Exception {

    // Instantiates a client
    Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
    String propertyName = "description";

    // Create the two filters
    Filter orFilter =
        CompositeFilter.or(
            PropertyFilter.eq(propertyName, "Feed cats"),
            PropertyFilter.eq(propertyName, "Buy milk"));

    // Build the query
    Query<Entity> query = Query.newEntityQueryBuilder().setKind("Task").setFilter(orFilter).build();

    // Get the results back from Datastore
    QueryResults<Entity> results = datastore.run(query);

    if (!results.hasNext()) {
      throw new Exception("query yielded no results");
    }

    while (results.hasNext()) {
      Entity entity = results.next();
      System.out.printf("Entity: %s%n", entity);
    }
  }
}

Node.js

To learn how to install and use the client library for Datastore mode, see Datastore mode client libraries. For more information, see the Datastore mode Node.js API reference documentation.

To authenticate to Datastore mode, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = "your Google Cloud project id";

// Imports the Cloud Datastore
const {Datastore, PropertyFilter, or} = require('@google-cloud/datastore');

async function queryFilterOr() {
  // Instantiate the Datastore
  const datastore = new Datastore();
  const query = datastore
    .createQuery('Task')
    .filter(
      or([
        new PropertyFilter('description', '=', 'Buy milk'),
        new PropertyFilter('description', '=', 'Feed cats'),
      ])
    );

  const [entities] = await datastore.runQuery(query);
  for (const entity of entities) {
    console.log(`Entity found: ${entity['description']}`);
  }
}

await queryFilterOr();
PHP

Snippet not available.

Python

To learn how to install and use the client library for Datastore mode, see Datastore mode client libraries. For more information, see the Datastore mode Python API reference documentation.

To authenticate to Datastore mode, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import datastore
from google.cloud.datastore import query


def query_filter_or(project_id: str) -> None:
    """Builds a union of two queries (OR) filter.

    Arguments:
        project_id: your Google Cloud Project ID
    """
    client = datastore.Client(project=project_id)

    or_query = client.query(kind="Task")
    or_filter = query.Or(
        [
            query.PropertyFilter("description", "=", "Buy milk"),
            query.PropertyFilter("description", "=", "Feed cats"),
        ]
    )

    or_query.add_filter(filter=or_filter)

    results = or_query.fetch()
    for result in results:
        print(result["description"])

Ruby

Snippet not available.

GQL

Snippet not available.

Firestore in Datastore mode supports combining filters with AND and OR operators. This example returns Task entities that are either starred or that are marked not done and have a priority of 4:
C#

Snippet not available.

Go

Snippet not available.

Java
Query query =
    Query.newEntityQueryBuilder()
        .setKind("Task")
        .setFilter(CompositeFilter.or(
            PropertyFilter.eq("starred", true)),
            CompositeFilter.and(
                PropertyFilter.eq("done", false),
                PropertyFilter.eq("priority", 4)))
        .build();

Node.js

Snippet not available.

PHP

Snippet not available.

Python
and_or_query = client.query(kind="Task")

query_filter = query.Or(
    [
        query.PropertyFilter("starred", "=", True),
        query.And([query.PropertyFilter("done", "=", False),
                    query.PropertyFilter("priority", "=", 4,),
        ]
        )   
    ]
)

and_or_query.add_filter(filter=query_filter)

results = and_or_query.fetch()
for result in results:
    print(result["description"])
Ruby

Snippet not available.

GQL

Snippet not available.

Key filters

To filter on the value of an entity's key, use the special property __key__:

C#

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore C# API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query query = new Query("Task")
{
    Filter = Filter.GreaterThan("__key__", _keyFactory.CreateKey("aTask"))
};

Go

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Go API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

key := datastore.NameKey("Task", "someTask", nil)
query := datastore.NewQuery("Task").FilterField("__key__", ">", key)

Java

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Java API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query<Entity> query =
    Query.newEntityQueryBuilder()
        .setKind("Task")
        .setFilter(PropertyFilter.gt("__key__", keyFactory.newKey("someTask")))
        .build();

Node.js

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Node.js API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const query = datastore
  .createQuery('Task')
  .filter('__key__', '>', datastore.key(['Task', 'someTask']));

PHP

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore PHP API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

$query = $datastore->query()
    ->kind('Task')
    ->filter('__key__', '>', $datastore->key('Task', 'someTask'));

Python

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Python API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import datastore

# For help authenticating your client, visit
# https://cloud.google.com/docs/authentication/getting-started
client = datastore.Client()

query = client.query(kind="Task")
first_key = client.key("Task", "first_task")
# key_filter(key, op) translates to add_filter('__key__', op, key).
query.key_filter(first_key, ">")

Ruby

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Ruby API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query = datastore.query("Task")
                 .where("__key__", ">", datastore.key("Task", "someTask"))

GQL


SELECT * FROM Task WHERE __key__ > KEY(Task, 'someTask')

When comparing for inequality, keys are ordered by the following criteria, in order:

  1. Ancestor path
  2. Entity kind
  3. Identifier (key name or numeric ID)

Elements of the ancestor path are compared similarly: by kind (string), then by key name or numeric ID. Kinds and key names are strings and are ordered by byte value; numeric IDs are integers and are ordered numerically. If entities with the same parent and kind use a mix of key name strings and numeric IDs, those with numeric IDs precede those with key names.

Queries on keys use indexes just like queries on properties and require custom indexes in the same cases, with a couple of exceptions: inequality filters or an ascending sort order on the key do not require a custom index, but a descending sort order on the key does. As with all queries, the development server creates appropriate entries in the index configuration file when a query that needs a custom index is used in the development environment.

Sort orders

A query sort order specifies

  • A property name.
  • A sort direction (ascending or descending). By default the sort order is ascending.

This example sorts Task entities by creation time in ascending order:

C#

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore C# API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query query = new Query("Task")
{
    Order = { { "created", PropertyOrder.Types.Direction.Ascending } }
};

Go

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Go API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query := datastore.NewQuery("Task").Order("created")

Java

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Java API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query<Entity> query =
    Query.newEntityQueryBuilder().setKind("Task").setOrderBy(OrderBy.asc("created")).build();

Node.js

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Node.js API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const query = datastore.createQuery('Task').order('created');

PHP

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore PHP API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

$query = $datastore->query()
    ->kind('Task')
    ->order('created');

Python

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Python API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import datastore

# For help authenticating your client, visit
# https://cloud.google.com/docs/authentication/getting-started
client = datastore.Client()

query = client.query(kind="Task")
query.order = ["created"]

Ruby

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Ruby API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query = datastore.query("Task")
                 .order("created", :asc)

GQL


SELECT * FROM Task ORDER BY created ASC

This example sorts Task entities by creation time in descending order:

C#

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore C# API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query query = new Query("Task")
{
    Order = { { "created", PropertyOrder.Types.Direction.Descending } }
};

Go

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Go API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query := datastore.NewQuery("Task").Order("-created")

Java

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Java API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query<Entity> query =
    Query.newEntityQueryBuilder().setKind("Task").setOrderBy(OrderBy.desc("created")).build();

Node.js

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Node.js API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const query = datastore.createQuery('Task').order('created', {
  descending: true,
});

PHP

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore PHP API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

$query = $datastore->query()
    ->kind('Task')
    ->order('created', Query::ORDER_DESCENDING);

Python

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Python API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import datastore

# For help authenticating your client, visit
# https://cloud.google.com/docs/authentication/getting-started
client = datastore.Client()

query = client.query(kind="Task")
query.order = ["-created"]

Ruby

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Ruby API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query = datastore.query("Task")
                 .order("created", :desc)

GQL


SELECT * FROM Task ORDER BY created DESC

If a query includes multiple sort orders, they are applied in the sequence specified. The following example sorts first by descending priority and then by ascending creation time:

C#

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore C# API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query query = new Query("Task")
{
    Order = { { "priority", PropertyOrder.Types.Direction.Descending },
        { "created", PropertyOrder.Types.Direction.Ascending } }
};

Go

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Go API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query := datastore.NewQuery("Task").Order("-priority").Order("created")

Java

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Java API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query<Entity> query =
    Query.newEntityQueryBuilder()
        .setKind("Task")
        .setOrderBy(OrderBy.desc("priority"), OrderBy.asc("created"))
        .build();

Node.js

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Node.js API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const query = datastore
  .createQuery('Task')
  .order('priority', {
    descending: true,
  })
  .order('created');

PHP

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore PHP API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

$query = $datastore->query()
    ->kind('Task')
    ->order('priority', Query::ORDER_DESCENDING)
    ->order('created');

Python

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Python API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import datastore

# For help authenticating your client, visit
# https://cloud.google.com/docs/authentication/getting-started
client = datastore.Client()

query = client.query(kind="Task")
query.order = ["-priority", "created"]

Ruby

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Ruby API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query = datastore.query("Task")
                 .order("priority", :desc)
                 .order("created", :asc)

GQL


SELECT * FROM Task ORDER BY priority DESC, created ASC

If no sort orders are specified, the results are returned in the order they are retrieved from Datastore mode.

Note: Because of the way Datastore mode executes queries, if a query specifies inequality filters on a property and sort orders on other properties, the property used in the inequality filters must be ordered before the other properties.

Special query types

Some specific types of query deserve special mention:

!= Not equal

Use the not-equal (!=) operator to return entities where the given property exists and does not match the comparison value.

C#

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore C# API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Not Applicable

Go

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Go API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

package datastore_snippets

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/datastore"
	"google.golang.org/api/iterator"
)

func queryNotEquals(w io.Writer, projectId string) error {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, projectId)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	q := datastore.NewQuery("TaskList")
	q.FilterField("Task", "!=", []string{"notASimpleTask"})

	it := client.Run(ctx, q)
	for {
		var dst struct {
			Task string
		}
		key, err := it.Next(&dst)
		if err == iterator.Done {
			break
		}

		if err != nil {
			return err
		}
		fmt.Fprintf(w, "Key retrieved: %v\n", key)
	}

	return nil
}

Java

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Java API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query<Entity> query =
    Query.newEntityQueryBuilder()
        .setKind("Task")
        .setFilter(PropertyFilter.neq("category", "Work"))
        .build();

Node.js

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Node.js API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Not Applicable

PHP

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore PHP API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Not Applicable

Python

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Python API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query = client.query(kind="Task")
query.add_filter("category", "!=", "work")

Ruby

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Ruby API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Not Applicable

GQL


SELECT * FROM Task WHERE category != 'work'

This query returns every Task entity where the category property exists and is set to any value other than Work.

This query does not return entities where the category property does not exist. Not-equal (!=) and NOT_IN queries exclude entities where the given property does not exist or where the property is excluded from indexing. A property exists when it's set to any value, including an empty string or null.

Limitations

Note the following limitations for != queries:

  • Only entities where the given property exists can match the query.
  • You can't combine NOT_IN and != in a compound query.
  • In a compound query, inequality filters (<, <=, >, >=, !=, NOT_IN) must all filter on the same property.

IN

Use the IN operator to combine up to 30 equality (==) clauses on the same property with a logical OR. An IN query returns entities where the given property matches any of the comparison values.

C#

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore C# API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Not Applicable

Go

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Go API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

package datastore_snippets

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/datastore"
	"google.golang.org/api/iterator"
)

func queryIn(w io.Writer, projectId string) error {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, projectId)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	q := datastore.NewQuery("TaskList")
	q.FilterField("Task", "in", []string{"simpleTask", "easyTask"})

	it := client.Run(ctx, q)
	for {
		var dst struct {
			Task string
		}
		key, err := it.Next(&dst)
		if err == iterator.Done {
			break
		}

		if err != nil {
			return err
		}
		fmt.Fprintf(w, "Key retrieved: %v\n", key)
	}

	return nil
}

Java

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Java API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query<Entity> query =
    Query.newEntityQueryBuilder()
        .setKind("Task")
        .setFilter(PropertyFilter.in("tag", ListValue.of("learn", "study")))
        .build();

Node.js

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Node.js API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Not Applicable

PHP

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore PHP API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Not Applicable

Python

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Python API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query = client.query(kind="Task")
query.add_filter("tag", "IN", ["learn", "study"])

Ruby

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Ruby API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Not Applicable

GQL


SELECT * FROM Task WHERE tag IN ARRAY('learn', 'study')

This query returns every Task entity where the tag property is set to learn or study. This includes Task entities where the tag property includes one of these values but not the other.

NOT_IN

Use the NOT_IN operator to combine up to 10 not-equal (!=) clauses on the same property with a logical AND. A NOT_IN query returns entities where the given property exists and does not match any of the comparison values.

C#

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore C# API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Not Applicable

Go

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Go API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

package datastore_snippets

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/datastore"
	"google.golang.org/api/iterator"
)

func queryNotIn(w io.Writer, projectId string) error {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, projectId)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	q := datastore.NewQuery("TaskList")
	q.FilterField("Task", "not-in", []string{"notASimpleTask", "notAnEasyTask"})

	it := client.Run(ctx, q)
	for {
		var dst struct {
			Task string
		}
		key, err := it.Next(&dst)
		if err == iterator.Done {
			break
		}

		if err != nil {
			return err
		}
		fmt.Fprintf(w, "Key retrieved: %v\n", key)
	}

	return nil
}

Java

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Java API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query<Entity> query =
    Query.newEntityQueryBuilder()
        .setKind("Task")
        .setFilter(PropertyFilter.not_in("category", ListValue.of("Work", "Chores", "School")))
        .build();

Node.js

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Node.js API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Not Applicable

PHP

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore PHP API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Not Applicable

Python

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Python API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

query = client.query(kind="Task")
query.add_filter("category", "NOT_IN", ["work", "chores", "school"])

Ruby

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Ruby API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Not Applicable

GQL


SELECT * FROM Task WHERE category NOT IN ARRAY('work', 'chores', 'school')

This query does not return entities where the category entity does not exist. Not-equal (!=) and NOT_IN queries exclude entities where the given property does not exist. A property exists when it's set to any value, including an empty string or null.

Limitations

Note the following limitations for NOT_IN queries:

  • Only entities where the given property exists can match the query.
  • You can't combine NOT_IN and != in a compound query.
  • In a compound query, inequality filters (<, <=, >, >=, !=, NOT_IN) must all filter on the same property.

Ancestor queries

An ancestor query limits its results to the specified entity and its descendants. This example returns all Task entities that have the specified TaskList entity as an ancestor:

C#

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore C# API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

Query query = new Query("Task")
{
    Filter = Filter.HasAncestor(_db.CreateKeyFactory("TaskList")
        .CreateKey(keyName))
};

Go

To learn how to install and use the client library for Cloud Datastore, see Cloud Datastore client libraries. For more information, see the Cloud Datastore Go API reference documentation.

To authenticate to Cloud Datastore, set up Application Default Credentials. For more information, see