「查詢游標」讓應用程式能夠方便地分批擷取查詢結果,而不會產生查詢偏移的負擔。執行擷取作業後,應用程式會取得一個游標,這個游標為不透明的 base64 編碼字串,用來標示最終擷取結果的索引位置。應用程式可以將這個字串儲存在 Datastore、Memcache、工作佇列工作酬載中,或以 HTTP GET 或 POST 參數的形式嵌入網頁中,然後將游標用作後續擷取作業的起點,從上次擷取結束的位置取得下一批結果。擷取作業也可以指定結束游標,用於限制傳回結果集的範圍。
在 Go 中,應用程式會呼叫 Iterator 值的 Cursor 方法,以此方式擷取查詢結果後,即可取得游標。為了從游標的位置擷取其他結果,應用程式會準備實體種類、篩選器和排序順序皆相同的相似查詢,並在執行擷取之前,將游標傳送至查詢的 Start 方法:
// 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()),})}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-07-08 (世界標準時間)。"],[[["This 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."],["Query 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."],["After 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."],["Cursors 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."],["Using 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."]]],[]]