Consistência de dados em consultas do Datastore
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Níveis de consistência de dados
As consultas do Datastore podem gerar resultados em dois níveis de
consistência:
- Consultas com consistência forte garantem os resultados mais recentes, mas podem levar mais tempo para serem concluídas.
- Consultas com consistência eventual costumam ser mais rápidas, mas podem retornar resultados desatualizados.
Em uma consulta com consistência eventual, os índices usados para coletar os resultados também são acessados com esse tipo de consistência. Consequentemente, essas consultas podem, algumas vezes, retornar entidades que não correspondem mais aos critérios de consulta originais, e as consultas fortemente consistentes são sempre consistentes de maneira transacional.
Consistência de dados da consulta do Datastore
As consultas retornam resultados com diferentes níveis de garantia de consistência, dependendo da natureza da consulta:
- As consultas de ancestral ficam dentro de um
grupo de entidades
e têm consistência forte por padrão, mas é possível atribuir uma consistência
eventual a elas. Para isso, basta definir a política de leitura do Cloud Datastore conforme descrito abaixo.
- As consultas de não ancestral sempre têm consistência eventual.
A busca de uma entidade por chave, também chamada de "pesquisa por chave", tem consistência
forte.
Como configurar a política de leitura do Datastore
Para melhorar o desempenho, defina a política de leitura do Datastore para que todas as leituras e consultas tenham consistência posterior. A API também permite definir explicitamente uma política de consistência forte, mas essa configuração não terá efeito prático, porque as consultas de não ancestral sempre têm consistência eventual, independentemente da política.
Também é possível definir o
prazo de chamada do Datastore, que é o tempo máximo, em segundos, que o aplicativo aguardará o Datastore retornar um resultado antes de ser cancelado com um erro. O prazo padrão é de 60 segundos. No momento, não é possível aumentá-lo, mas apenas diminuí-lo para garantir que uma determinada operação falhe rapidamente. Por exemplo, para retornar uma resposta mais rápida ao usuário.
Para definir a política de leitura do Datastore em Java, crie uma
configuração de serviço do Datastore (
DatastoreServiceConfig
) usando a classe auxiliar aninhada
DatastoreServiceConfig.Builder
e transmita uma instância da classe
ReadPolicy
. O seguinte exemplo mostra como definir a política de leitura, o prazo de chamada ou ambos.
A seguir
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
Última atualização 2025-09-04 UTC.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-04 UTC."],[[["\u003cp\u003eThis API supports first-generation runtimes and is relevant when upgrading to second-generation runtimes, while migration to Java 11/17 requires a separate migration guide.\u003c/p\u003e\n"],["\u003cp\u003eDatastore queries offer two consistency levels: strongly consistent queries, which guarantee the freshest results but may be slower, and eventually consistent queries, which are generally faster but may return stale results.\u003c/p\u003e\n"],["\u003cp\u003eAncestor queries are strongly consistent by default but can be set to eventually consistent, while non-ancestor queries are always eventually consistent.\u003c/p\u003e\n"],["\u003cp\u003eThe Datastore read policy can be set to eventually consistent to improve performance, and the call deadline can be adjusted to control the maximum wait time for a Datastore operation.\u003c/p\u003e\n"],["\u003cp\u003eDevelopers can use the \u003ccode\u003eDatastoreServiceConfig\u003c/code\u003e to set the read policy and/or the call deadline for Datastore operations, using the \u003ccode\u003eReadPolicy\u003c/code\u003e for consistency and \u003ccode\u003ewithDeadline\u003c/code\u003e for the time limit, and can use the \u003ccode\u003eDatastoreServiceFactory\u003c/code\u003e to get a \u003ccode\u003eDatastoreService\u003c/code\u003e instance with the desired configuration.\u003c/p\u003e\n"]]],[],null,["# Data Consistency in Datastore Queries\n\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| java-gen2\n|\n| /services/access). If you are updating to the App Engine Java 11/17 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/java-differences) to learn about your migration options for legacy bundled services.\n\nData consistency levels\n-----------------------\n\nDatastore queries can deliver their results at either of two consistency\nlevels:\n\n- [*Strongly consistent*](https://en.wikipedia.org/wiki/Strong_consistency) queries guarantee the freshest results, but may take longer to complete.\n- [*Eventually consistent*](https://en.wikipedia.org/wiki/Eventual_consistency) queries generally run faster, but may occasionally return stale results.\n\nIn an eventually consistent query, the indexes used to gather the results are also accessed with eventual consistency. Consequently, such queries may sometimes return entities that no longer match the original query criteria, while strongly consistent queries are always transactionally consistent.\n\nDatastore query data consistency\n--------------------------------\n\nQueries return their results with different levels of consistency guarantee, depending on the nature of the query:\n\n- [Ancestor queries](/appengine/docs/legacy/standard/java/datastore/queries#ancestor_queries) (those within an [entity group](/appengine/docs/legacy/standard/java/datastore/entities#Ancestor_paths)) are strongly consistent by default, but can instead be made eventually consistent by setting the Datastore read policy (see below).\n- Non-ancestor queries are always eventually consistent.\n\nFetching an entity by key, which is also called \"lookup by key\", is strongly\nconsistent.\n\n\u003cbr /\u003e\n\nSetting the Datastore read policy\n---------------------------------\n\nTo improve performance, you can set the Datastore *read policy* so that all reads and queries are eventually consistent. (The API also allows you to explicitly set a strong consistency policy, but this setting will have no practical effect, since non-ancestor queries are always eventually consistent regardless of policy.)\nYou can also set the Datastore *call deadline* , which is the maximum time, in seconds, that the application will wait for Datastore to return a result before aborting with an error. The default deadline is 60 seconds; it is not currently possible to set it higher, but you can adjust it downward to ensure that a particular operation fails quickly (for instance, to return a faster response to the user).\n\n\u003cbr /\u003e\n\nTo set the Datastore read policy in Java, you construct a *Datastore service configuration* ([`DatastoreServiceConfig`](/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/datastore/DatastoreServiceConfig)), using the nested helper class [`DatastoreServiceConfig.Builder`](/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/datastore/DatastoreServiceConfig.Builder), and pass it an instance of class [`ReadPolicy`](/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/datastore/ReadPolicy). The following example shows how to set the read policy, the call deadline, or both:\n\n\u003cbr /\u003e\n\n double deadline = 5.0;\n\n // Construct a read policy for eventual consistency\n ReadPolicy policy = new ReadPolicy(ReadPolicy.Consistency.EVENTUAL);\n\n // Set the read policy\n DatastoreServiceConfig eventuallyConsistentConfig =\n DatastoreServiceConfig.Builder.withReadPolicy(policy);\n\n // Set the call deadline\n DatastoreServiceConfig deadlineConfig = DatastoreServiceConfig.Builder.withDeadline(deadline);\n\n // Set both the read policy and the call deadline\n DatastoreServiceConfig datastoreConfig =\n DatastoreServiceConfig.Builder.withReadPolicy(policy).deadline(deadline);\n\n // Get Datastore service with the given configuration\n DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(datastoreConfig);\n\nWhat's next?\n------------\n\n- [Learn how to specify what a query returns and further control query results](/appengine/docs/legacy/standard/java/datastore/retrieving-query-results).\n- Learn the [common restrictions](/appengine/docs/legacy/standard/java/datastore/query-restrictions) for queries on Datastore.\n- Learn about [query cursors](/appengine/docs/legacy/standard/java/datastore/query-cursors), which allow an application to retrieve a query's results in convenient batches.\n- Learn the [basic syntax and structure of queries](/appengine/docs/legacy/standard/java/datastore/queries) for Datastore."]]