Skip to content

Instantly share code, notes, and snippets.

@glynnbird
Last active January 10, 2019 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glynnbird/569480123d412f55d0ec142a198f7f24 to your computer and use it in GitHub Desktop.
Save glynnbird/569480123d412f55d0ec142a198f7f24 to your computer and use it in GitHub Desktop.
Using Pagination with Cloudant Query

Let's say we want to query a data set and get paginated result sets. In this example we're going to query a set of cities of the world, looking for those based in the USA. Our query is:

{ 
  selector: { country: 'US'}, 
  limit: 50
}

The Node.js to perform this search is as follows:

const Cloudant = require('@cloudant/cloudant')
const cloudant = Cloudant({url: process.env.COUCH_URL})
const db = cloudant.db.use('cities')

db.find({ selector: { country: 'US'}, limit: 50}).then(console.log)

The data returned follows the following form:

{
  "docs": [  ... ],
  "bookmark": ""
}

The returned documents appear in the docs array and the bookmark is our key to the next page of data. To get the next page simply pass the returned "bookmark" in your next query:

const Cloudant = require('@cloudant/cloudant')
const cloudant = Cloudant({url: process.env.COUCH_URL})
const db = cloudant.db.use('cities')

// this is the bookmark taken from the first result set
const bookmark = 'g1AAAAA-eJzLYWBgYMpgSmHgKy5JLCrJTq2MT8lPzkzJBYqzmxgampoYGoGkOWDSyBJZAO7zD4c'

// repeat the query but pass the preceeding bookmark in too
db.find({ selector: { country: 'US'}, limit: 50, bookmark: bookmark}).then(console.log)

The query should be the same as the first one, but with the addition of the bookmark attribute. The third page of results can be queried by passing the second bookmark into a third request, and so on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment