【发布时间】:2016-02-07 06:52:07
【问题描述】:
我想从带有可选分页的端点返回“帖子”列表。 每个查询我需要 100 个结果。 我写的代码如下,它似乎不起作用。 我指的是Objectify Wiki的一个例子
我知道的另一个选项是使用query.offset(100);
但我在某处读到这只是加载整个表,然后忽略前 100 个不是最佳的条目。
我想这一定是一个常见的用例,并且会有最佳解决方案。
public CollectionResponse<Post> getPosts(@Nullable @Named("cursor") String cursor,User auth) throws OAuthRequestException {
if (auth!=null){
Query<Post> query = ofy().load().type(Post.class).filter("isReviewed", true).order("-timeStamp").limit(100);
if (cursor!=null){
query.startAt(Cursor.fromWebSafeString(cursor));
log.info("Cursor received :" + Cursor.fromWebSafeString(cursor));
} else {
log.info("Cursor received : null");
}
QueryResultIterator<Post> iterator = query.iterator();
for (int i = 1 ; i <=100 ; i++){
if (iterator.hasNext()) iterator.next();
else break;
}
log.info("Cursor generated :" + iterator.getCursor());
return CollectionResponse.<Post>builder().setItems(query.list()).setNextPageToken(iterator.getCursor().toWebSafeString()).build();
} else throw new OAuthRequestException("Login please.");
}
这是一个使用偏移量的代码,似乎工作正常。
@ApiMethod(
name = "getPosts",
httpMethod = ApiMethod.HttpMethod.GET
)
public CollectionResponse<Post> getPosts(@Nullable @Named("offset") Integer offset,User auth) throws OAuthRequestException {
if (auth!=null){
if (offset==null) offset = 0;
Query<Post> query = ofy().load().type(Post.class).filter("isReviewed", true).order("-timeStamp").offset(offset).limit(LIMIT);
log.info("Offset received :" + offset);
log.info("Offset generated :" + (LIMIT+offset));
return CollectionResponse.<Post>builder().setItems(query.list()).setNextPageToken(String.valueOf(LIMIT + offset)).build();
} else throw new OAuthRequestException("Login please.");
}
【问题讨论】:
标签: google-app-engine pagination google-cloud-endpoints objectify google-cloud-datastore