查询游标让应用以便捷的批量方式检索查询结果,而且不会因查询偏移而产生开销。执行检索操作后,应用会获得一个游标,该游标是一个不透明的 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"]],["最后更新时间 (UTC):2025-03-07。"],[[["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."]]],[]]