2011-07-29 37 views
2

我有GAE数据存储中的游戏列表,我想查询它们的固定数量,从某个偏移量开始,即得到接下来的25个游戏,从ID为“75”的表单输入开始。App Engine Java:用于设置查询限制和起始偏移量的语法。

PersistenceManager pm = PMF.get().getPersistenceManager(); // from Google examples 
Query query = pm.newQuery(Game.class); // objects of class Game are stored in datastore 
query.setOrdering("creationDate asc"); 
/* querying for open games, not created by this player */ 
query.setFilter("state == Game.STATE_OPEN && serverPlayer.id != :playerId"); 
String playerId = "my-player-id"; 
List<Game> games = query.execute(playerId); // if there's lots of games, returned list has more entries, than user needs to see at a time 
//... 

现在我需要扩展该查询来获取只有25个游戏和只有游戏后ID为“75”的条目。因此,用户可以浏览打开的游戏,一次只能获取其中的25个。 我知道GAE数据存储有很多示例,但这些示例大部分都是Python,包括用于设置查询限制的示例代码。 我正在寻找一个可用的Java代码示例,到目前为止找不到。

+0

使用不等于查询过滤掉(我假定是)一个结果是浪费资源 - SDK必须执行两个查询来满足这个要求。相反,从返回的结果集中筛选出您不想要的单个结果。 –

+0

最多可以有5场比赛,属于有问题的球员。但实际上在查询数以百计的游戏时,1或5没有任何区别,所以你明白了,我只是从查询中移出“!=”逻辑。 – i4niac

回答

4

这听起来像你想通过查询游标促进分页。请参阅:http://code.google.com/appengine/docs/java/datastore/queries.html#Query_Cursors

the Google doc

public class ListPeopleServlet extends HttpServlet { 

    @Override 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 

     DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); 
     Query q = new Query("Person"); 
     PreparedQuery pq = datastore.prepare(q); 
     int pageSize = 15; 

     resp.setContentType("text/html"); 
     resp.getWriter().println("<ul>"); 

     FetchOptions fetchOptions = FetchOptions.Builder.withLimit(pageSize); 
     String startCursor = req.getParameter("cursor"); 

     // If this servlet is passed a cursor parameter, let's use it 
     if (startCursor != null) { 
      fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor)); 
     } 

     QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions); 
     for (Entity entity : results) { 
      resp.getWriter().println("<li>" + entity.getProperty("name") + "</li>"); 
     } 
     resp.getWriter().println("</ul>"); 

     String cursor = results.getCursor().toWebSafeString(); 

     // Assuming this servlet lives at '/people' 
     resp.getWriter().println(
      "<a href='/people?cursor=" + cursor + "'>Next page</a>"); 
    } 
} 
+0

嗯...看起来像我需要的,除了一个限制:**你不能使用游标与查询使用IN或!=过滤器操作符。**例如使用另一个API,而不是持久性管理器,但不应该是一个问题,我会试试看,看看它是否适合我。 – i4niac

+0

感谢这比文档更清晰!为什么他们不能只提供一个代码样本? –

+0

好的,但为什么getOffset,getPrefetchSize,getChunkSize返回null,一旦光标被设置为fetchOptions? – alex