如何在Google Cloud Datastore查询中获取每个实体对应的cursor?
解决方案
可以实现,Node.js版Google Cloud Datastore客户端提供了对应配置支持获取每个实体的专属cursor,操作逻辑如下:
执行查询时传入showCursor: true配置项,开启返回实体cursor的能力。开启后每个返回的实体都会通过Datastore.KEY符号属性携带对应cursor,遍历结果实体列表提取cursor挂载到实体对象上,即可得到你期望的返回格式。
完整代码示例
const { Datastore } = require('@google-cloud/datastore'); const datastore = new Datastore(); // 原有查询逻辑不变 const query = datastore .createQuery(['EntityType']) .limit(2) .start(start); // 执行查询时新增showCursor配置 const [entities, queryInfo] = await datastore.runQuery(query, { showCursor: true }); // 提取每个实体的cursor并挂载 const entitiesWithCursor = entities.map(entity => { // 从符号属性中获取当前实体对应的cursor const entityCursor = entity[Datastore.KEY].cursor; return { ...entity, cursor: entityCursor }; }); // 最终输出格式和你期望的一致 const finalResult = [entitiesWithCursor, queryInfo];
注意事项
- 实体cursor和当前查询的过滤条件、排序规则强绑定,只能用于同一个查询的分页场景,修改查询配置后cursor会失效
showCursor配置需要依赖@google-cloud/datastorev2.0.0及以上版本,如果你使用的依赖版本过低需要先升级
内容的提问来源于stack exchange,提问作者Riley Conrardy
相关产品推荐
相关产品推荐

