Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Os cursores de consulta permitem a recuperação, por parte de um aplicativo, dos resultados de uma consulta em lotes convenientes, sendo o uso recomendado em deslocamentos inteiros para paginação.
Saiba mais sobre como estruturar consultas para o aplicativo em Consultas.
Cursores de consulta
Os cursores de consulta permitem a recuperação, por parte de um aplicativo, dos resultados de uma consulta em lotes convenientes, evitando a sobrecarga do deslocamento dessa consulta. Após executar uma
operação de recuperação, o aplicativo recebe um
cursor, que é uma string opaca codificada em base64 que marca a posição do índice do
último resultado recuperado. O aplicativo pode salvar essa string, por exemplo, no
Datastore, no Memcache, em um payload de tarefa do Task Queue ou incorporada em
uma página da Web como parâmetro HTTP GET ou POST. Depois, ele pode usar o cursor como
ponto de partida para uma operação de recuperação subsequente. Nesse caso, o lote seguinte
de resultados será conseguido a partir do ponto em que a recuperação anterior terminou. É possível que
uma recuperação também especifique um cursor de término para limitar a extensão do conjunto de resultados retornados.
Deslocamentos versus cursores
O Datastore é compatível com deslocamentos de números inteiros, mas é melhor
evitá-los. Em vez disso, use cursores. O uso de um deslocamento evita apenas o retorno de entidades ignoradas ao aplicativo, mas é possível recuperá-las internamente. Na verdade, as entidades ignoradas afetam a latência da consulta. Além disso, o aplicativo será cobrado pelas operações de leitura necessárias para a recuperação dessas entidades. Use cursores em vez de deslocamentos para evitar todos esses custos.
Exemplo de cursor de consulta
No Go, um aplicativo recebe um cursor depois de recuperar os resultados da consulta chamando
o método Cursor do valor Iterator. Para recuperar
outros resultados a partir do ponto do cursor, o aplicativo prepara uma
consulta semelhante com o mesmo filtro, ordem de classificação e
tipo de entidade, além de transmitir o cursor para o método
Start da consulta, antes de executar a recuperação:
// Create a query for all Person entities.q:=datastore.NewQuery("Person")// If the application stored a cursor during a previous request, use it.item,err:=memcache.Get(ctx,"person_cursor")iferr==nil{cursor,err:=datastore.DecodeCursor(string(item.Value))iferr==nil{q=q.Start(cursor)}}// Iterate over the results.t:=q.Run(ctx)for{varpPerson_,err:=t.Next(&p)iferr==datastore.Done{break}iferr!=nil{log.Errorf(ctx,"fetching next Person: %v",err)break}// Do something with the Person p}// Get updated cursor and store it for next time.ifcursor,err:=t.Cursor();err==nil{memcache.Set(ctx,&memcache.Item{Key:"person_cursor",Value:[]byte(cursor.String()),})}
Limitações dos cursores
Os cursores estão sujeitos às seguintes limitações:
Um cursor é usado somente pelo mesmo projeto que executou a consulta original e para continuar a mesma consulta. Para usar o cursor em uma operação de recuperação posterior, reconstitua na íntegra a consulta original, incluindo o mesmo tipo de entidade, filtro de ancestrais e de propriedades e ordens de classificação. Não é possível recuperar resultados usando um cursor sem configurar a mesma consulta que o gerou originalmente.
Cursores nem sempre funcionam como esperado em uma consulta que usa um filtro de desigualdade ou uma ordem de classificação em uma propriedade com valores múltiplos. A lógica de eliminar a duplicação para essas propriedades não se mantém entre as recuperações. Assim, é possível que o mesmo resultado seja retornado mais de uma vez.
Novas versões do App Engine podem alterar os detalhes de implementação internos, invalidando cursores que dependem deles. Se um aplicativo tentar usar um
cursor que não é mais válido, o Datastore
retornará
um erro.
Cursores e atualizações de dados
A posição do cursor é definida como o local na lista de resultados após o último
resultado retornado. Um cursor não é uma posição relativa na lista,
não é um deslocamento, e sim um marcador para o qual o Datastore pode pular
ao iniciar uma varredura de índice em busca de resultados. Caso os resultados de uma consulta sofram
alteração entre os usos de um cursor, ela refletirá apenas as alterações ocorridas nos
resultados após o cursor. Se na consulta aparecer um novo resultado antes da posição do cursor, ele não será retornado quando forem recuperados os resultados após o cursor.
Da mesma forma, caso uma entidade não seja mais o resultado de uma consulta, mesmo tendo aparecido antes do cursor, os resultados após o cursor não serão alterados. Caso
o último resultado retornado seja removido do conjunto de resultados, o cursor ainda saberá
como localizar o próximo.
Ao recuperar os resultados da consulta, é possível usar um cursor inicial e um cursor final
para retornar um grupo contínuo de resultados do Datastore. Usar
um cursor de início e de término na recuperação de resultados não garante que o
tamanho dos resultados seja o mesmo de quando os cursores foram gerados.
As entidades podem ser adicionadas ou excluídas do Datastore entre o
momento em que os cursores são gerados e o momento em que são usados em uma consulta.
[[["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-03 UTC."],[[["\u003cp\u003eThis API is designed for first-generation runtimes and is crucial when upgrading to corresponding second-generation runtimes, with a migration guide provided for App Engine Go 1.12+ users.\u003c/p\u003e\n"],["\u003cp\u003eQuery cursors enable applications to retrieve query results in batches, providing a more efficient method of pagination compared to using integer offsets, as they avoid retrieving skipped entities internally.\u003c/p\u003e\n"],["\u003cp\u003eAfter retrieving results, a cursor, which is an encoded string, can be obtained to mark the last result's position, allowing the application to save it and use it as a starting point for the next retrieval operation.\u003c/p\u003e\n"],["\u003cp\u003eCursors are limited to use by the originating application and require an exact replication of the initial query's conditions to be reused, while also being susceptible to invalidation from new App Engine releases.\u003c/p\u003e\n"],["\u003cp\u003eUsing cursors for pagination is preferred over offsets because it allows you to avoid costs and latency associated with retrieving entities internally that will just be skipped, in addition to being able to specify an end cursor to limit results.\u003c/p\u003e\n"]]],[],null,["# Query Cursors\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| go\n| /services/access). If you are updating to the App Engine Go 1.12+ runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/go-differences) to learn about your migration options for legacy bundled services.\n\n*Query cursors* allow an application to retrieve a query's results in convenient\nbatches, and are recommended over using integer offsets for pagination.\nSee [Queries](/appengine/docs/legacy/standard/go111/datastore/queries) for more information on structuring queries for your app.\n\nQuery cursors\n-------------\n\n*Query cursors* allow an application to retrieve a query's results in convenient\nbatches without incurring the overhead of a query offset. After performing a\n[retrieval operation](/appengine/docs/legacy/standard/go111/datastore/retrieving-query-results), the application can obtain a\ncursor, which is an opaque base64-encoded string marking the index position of\nthe last result retrieved. The application can save this string, for example in\nDatastore, in Memcache, in a Task Queue task payload, or embedded in\na web page as an HTTP `GET` or `POST` parameter, and can then use the cursor as\nthe starting point for a subsequent retrieval operation to obtain the next batch\nof results from the point where the previous retrieval ended. A retrieval can\nalso specify an end cursor, to limit the extent of the result set returned.\n\nOffsets versus cursors\n----------------------\n\nAlthough Datastore supports integer offsets, you should avoid\nusing them. Instead, use cursors. Using an offset only avoids returning the\nskipped entities to your application, but these entities are still retrieved\ninternally. The skipped entities do affect the latency of the query, and your\napplication is billed for the read operations required to retrieve them. Using\ncursors instead of offsets lets you avoid all these costs.\n\nQuery cursor example\n--------------------\n\nIn Go, an application obtains a cursor after retrieving query results by calling\nthe `Iterator` value's [`Cursor`](/appengine/docs/legacy/standard/go111/datastore/reference#Iterator.Cursor) method. To retrieve\nadditional results from the point of the cursor, the application prepares a\nsimilar query with the same entity kind, filters, and\nsort orders, and passes the cursor to the query's\n[`Start`](/appengine/docs/legacy/standard/go111/datastore/reference#Query.Start) method before performing the retrieval: \n\n // Create a query for all Person entities.\n q := datastore.NewQuery(\"Person\")\n\n // If the application stored a cursor during a previous request, use it.\n item, err := memcache.Get(ctx, \"person_cursor\")\n if err == nil {\n \tcursor, err := datastore.DecodeCursor(string(item.Value))\n \tif err == nil {\n \t\tq = q.Start(cursor)\n \t}\n }\n\n // Iterate over the results.\n t := q.Run(ctx)\n for {\n \tvar p Person\n \t_, err := t.Next(&p)\n \tif err == datastore.Done {\n \t\tbreak\n \t}\n \tif err != nil {\n \t\tlog.Errorf(ctx, \"fetching next Person: %v\", err)\n \t\tbreak\n \t}\n \t// Do something with the Person p\n }\n\n // Get updated cursor and store it for next time.\n if cursor, err := t.Cursor(); err == nil {\n \tmemcache.Set(ctx, &memcache.Item{\n \t\tKey: \"person_cursor\",\n \t\tValue: []byte(cursor.String()),\n \t})\n }\n\n| **Caution:** Be careful when passing a Datastore cursor to a client, such as in a web form. Although the client cannot change the cursor value to access results outside of the original query, it is possible for it to decode the cursor to expose information about result entities, such as the application ID, entity kind, key name or numeric ID, ancestor keys, and properties used in the query's filters and sort orders. If you don't want users to have access to that information, you can encrypt the cursor, or store it and provide the user with an opaque key.\n\n### Limitations of cursors\n\nCursors are subject to the following limitations:\n\n- A cursor can be used only by the same application that performed the original query, and only to continue the same query. To use the cursor in a subsequent retrieval operation, you must reconstitute the original query exactly, including the same entity kind, ancestor filter, property filters, and sort orders. It is not possible to retrieve results using a cursor without setting up the same query from which it was originally generated.\n- Cursors don't always work as expected with a query that uses an inequality filter or a sort order on a property with multiple values. The de-duplication logic for such multiple-valued properties does not persist between retrievals, possibly causing the same result to be returned more than once.\n- New App Engine releases might change internal implementation details, invalidating cursors that depend on them. If an application attempts to use a cursor that is no longer valid, Datastore returns an error.\n\n### Cursors and data updates\n\nThe cursor's position is defined as the location in the result list after the\nlast result returned. A cursor is not a relative position in the list\n(it's not an offset); it's a marker to which Datastore can jump\nwhen starting an index scan for results. If the results for a query change\nbetween uses of a cursor, the query notices only changes that occur in results\nafter the cursor. If a new result appears before the cursor's position for the\nquery, it will not be returned when the results after the cursor are fetched.\nSimilarly, if an entity is no longer a result for a query but had appeared\nbefore the cursor, the results that appear after the cursor do not change. If\nthe last result returned is removed from the result set, the cursor still knows\nhow to locate the next result.\n\nWhen retrieving query results, you can use both a start cursor and an end cursor\nto return a continuous group of results from Datastore. When\nusing a start and end cursor to retrieve the results, you are not guaranteed\nthat the size of the results will be the same as when you generated the cursors.\nEntities may be added or deleted from Datastore between the\ntime the cursors are generated and when they are used in a query.\n\nWhat's next?\n------------\n\n- [Learn how to specify what a query returns and further control query\n results](/appengine/docs/legacy/standard/go111/datastore/retrieving-query-results).\n- Learn the [common restrictions](/appengine/docs/legacy/standard/go111/datastore/query-restrictions) for queries on Datastore.\n- [Understand data consistency](/appengine/docs/legacy/standard/go111/datastore/data-consistency) and how data consistency works with different types of queries on Datastore.\n- Learn the [basic syntax and structure of queries](/appengine/docs/legacy/standard/go111/datastore/queries) for Datastore."]]