Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pagination in CouchDB?

How would I go about implementation the queries required for pagination?

Basically, when page 1 is requested, get the first 5 entries. For page 2, get the next 5 and so on.

I plan to use this via the couchdb-python module, but that shouldn't make any difference to the implementation.

like image 802
dbr Avatar asked Nov 23 '08 05:11

dbr


1 Answers

The CouchDB Guide has a good discussion of pagination, including lots of sample code, here: http://guide.couchdb.org/draft/recipes.html#pagination Here's their algorithm:

  • Request rows_per_page + 1 rows from the view
  • Display rows_per_page rows, store last row as next_startkey
  • As page information, keep startkey and next_startkey
  • Use the next_* values to create the next link, and use the others to create the previous link

N.B.: The proper way to fetch pages in CouchDB is by specifying a starting key, not a starting index like you might think. But how do you know what key to start the 2nd page on? The clever solution: "Instead of requesting 10 rows for a page, you request 11 rows, but display only 10 and use the values in the 11th row as the startkey for the next page."

If you expect to have multiple documents emit identical keys, you'll need to use startdocid in addition to startkey to paginate correctly. The reason is that startkey alone will no longer be sufficient to uniquely identify a row. Those parameters are useless if you don't provide a startkey. In fact, CouchDB will first look at the startkey parameter, then it will use the startdocid parameter to further redefine the beginning of the range if multiple potential staring rows have the same key but different document IDs. Same thing for the enddocid.

like image 152
AlexChaffee Avatar answered Sep 19 '22 04:09

AlexChaffee