Pagination in CouchDB?

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.

Leave a Comment