Tuesday, October 1, 2013

Pagination with Couchbase

If you have to deal with a large number of documents when doing queries against a Couchbase cluster it is important to use pagination to get rows by page. You can find some information in the documentation in the chapter "Pagination", but I want to go in more details and sample code in this article.


For this example I will start by creating a simple view based on the beer-sample dataset, the view is used to find brewery by country:

function (doc, meta) {
  if (doc.type == "brewery" && doc.country){
   emit(doc.country);
  } 
}


This view list all the breweries by country, the index looks like:

Doc idKeyValue
bersaglierArgentinanull
cervecera_jeromeArgentinanull
brouwerij_nacional_balashiArubanull
australian_brewing_corporationAustralianull
carlton_and_united_breweriesAustralianull
coopers_breweryAustralianull
foster_s_australia_ltdAustralianull
gold_coast_breweryAustralianull
lion_nathan_australia_hunter_streetAustralianull
little_creatures_breweryAustralianull
malt_shovel_breweryAustralianull
matilda_bay_brewingAustralianull
.........
.........
.........
yellowstone_valley_brewingUnited Statesnull
yuengling_son_brewingUnited Statesnull
zea_rotisserie_and_breweryUnited Statesnull
fosters_tien_gangViet Namnull
hue_breweryViet Namnull


So now you want to navigate in this index with a page size of 5 rows.