Get query results one page at a time

When working with large datasets, you might want to segment query responses. You can do this using the Fauna pagination feature, which allows you to iterate through the result set in manageable page sizes.

Results larger than a page include a pagination cursor that you use to traverse pages.

Define a page size

This exercise paginates the CoffeeBean collection documents. The collection should currently have at least three documents, so a documents per page limit of two is used to trigger pagination.

If you want to create more pages, create them as described in the Fauna at-a-glance tutorial.

Define your page size and get the first page by calling the CoffeeBean paginate() method, passing 2 as a parameter to indicate that you want two documents per page:

CoffeeBean.all().paginate(2)
{
  data: [
    {
      id: "366190504817197124",
      coll: CoffeeBean,
      ts: Time("2023-06-03T14:58:37.770Z"),
      Owner: "metad plc",
      Country_of_Origin: "Ethiopia",
      Species: "Arabica",
      Harvest_Year: 2014,
      Quality_Parameters: {
        Aroma: 8.67,
        Flavor: 8.83,
        Balance: 8.42
      },
      Altitude: {
        unit_of_measurement: "m",
        mean: 2075
      },
      Best_of_Class: Date("2023-06-03")
    },
    {
      id: "366190711733747780",
      coll: CoffeeBean,
      ts: Time("2023-06-03T14:58:52.120Z"),
      Species: "Arabica",
      Owner: "Healthy Grounds",
      Country_of_Origin: "Guatemala",
      Harvest_Year: "",
      Quality_Parameters: {
        Aroma: 8.42,
        Flavor: 8.5,
        Balance: 8.42
      },
      Altitude: {
        unit_of_measurement: "m",
        mean: 1700
      },
      Best_of_Class: Date("2023-06-03")
    }
  ],
  after: "hdWDxoJqQ29mZmVlQ...elided...YIaZHuUrRohcjHgAg=="
}

The response is terminated with an after cursor that you use to get the next page.

Fetch the next page using the cursor

To get the next page, use the after cursor returned with the previous document set directly in the Set Set.paginate() method:

Set.paginate("hdWDxoJqQ29mZmVlQ...elided...YIaZHuUrRohcjHgAg==")
{
  data: [
    {
      id: "366521185649819716",
      coll: CoffeeBean,
      ts: Time("2023-06-03T14:42:23.670Z"),
      Species: "Robusta",
      Owner: "nishant gurjer",
      Country_of_Origin: "India",
      Harvest_Year: 2017,
      Quality_Parameters: {
        Aroma: 8,
        Flavor: 7.75,
        Balance: 7.92
      },
      Altitude: {
        unit_of_measurement: "m",
        mean: 3170
      }
    }
  ]
}

The response includes, at most, the next two documents, which is the page size you previously defined. Because the dataset used in this exercise has three documents, the Set.paginate() request for the next page returned one document.

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!