2

I'm using the new gcloud-java API (https://github.com/GoogleCloudPlatform/gcloud-java/tree/master/gcloud-java-datastore/src/main/java/com/google/cloud/datastore) for working with the Cloud Datastore. My specific question is on using GQL for pagination with cursors. I was able to page through the results one page at a time in the forward direction using cursors, but not having any luck with paging backwards.

Example Scenario:

Let's say I've 20 entities in a Kind with IDs 1 through 20. I have a page size of 5. Once I'm on the 3rd page (IDs 11 through 15), if I need to go one page back; i.e. retrieve IDs 6 through 10, what would be the correct GQL/sample code? Again, I prefer not to use offset with a number, but would like to use Cursors.

From what I can tell (actually tested), it looks like one needs to keep track of Start/End cursors for each page as they navigate in the forward direction, then use the saved cursors when there is a need to go back. I just want to make sure if this is the correct/only way or there is a simpler way to accomplish this.

Thanks in advance for your help.

Sai Pullabhotla
  • 2,207
  • 17
  • 17

1 Answers1

3

If you add to your original query a sort by key (appended to the end of your "order by" clause), you should be able to reverse each property's sort order and use the latest cursor from your original query to get results in reverse.

Suppose you've iterated through some of the values from your forward query's QueryResults. You can call QueryResults's cursorAfter() method, which will return a cursor pointing right after the last result you saw from your original query. Now you can issue a new query (with the opposite sort order on each property, including the key property) using that cursor as the start cursor. You'll probably want to skip the first result, since it will be the last result you saw from the original query.

Ajay Kannan
  • 201
  • 2
  • 3
  • Thanks. So, there is really no way to traverse the result set in the reverse direction from a given Cursor when the results are sorted on a non-key column? Is this a Datastore limitation or the API limitation? – Sai Pullabhotla Jun 17 '16 at 17:51
  • I should have used more general wording in my original response. If you add the key to your sort order clause (at the end, after other properties you wish to sort on), and reverse all your sort orders (including the key sort order), you should get the results in reverse. I'll edit the original response to reflect this. – Ajay Kannan Jun 21 '16 at 03:37