Paginate query results
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.
The examples in this tutorial use Fauna’s demo data.
Define a page size
Use pageSize()
to paginate a
large Set. You must pass a size argument to configure the number of
items returned per page.
The following query calls
pageSize()
with a size of
2
on the Product
collection’s sortedByPriceLowToHigh
index.
Product.sortedByPriceLowToHigh()
.pageSize(2)
pageSize()
limits each page of
results to two items or less. If there are additional pages, the response
includes an after
cursor you can use to get the next page.
{
data: [
{
id: "393605620096303168",
coll: Product,
ts: Time("2099-03-28T12:53:40.750Z"),
name: "limes",
...
},
{
id: "393605620102594624",
coll: Product,
ts: Time("2099-03-28T12:53:40.750Z"),
name: "cilantro",
...
}
],
after: "hdWCxmd..."
}
Fetch the next page
To get the next page, pass the after
cursor to
Set.paginate()
:
Set.paginate("hdWCxmd...")
The response’s set includes up to size items.
If there are additional pages, the response includes an after
cursor for the next page. Use another
Set.paginate()
call to
fetch this page.
{
data: [
{
id: "393605620101546048",
coll: Product,
ts: Time("2099-03-28T12:53:40.750Z"),
name: "limes",
...
},
{
id: "393605620098400320",
coll: Product,
ts: Time("2099-03-28T12:53:40.750Z"),
name: "limes",
...
}
],
after: "abc123..."
}
Cursor expiration
The after
cursor is stable in the sense that pagination through a set is done
for a fixed snapshot time, giving you a view of your data as it existed across
the whole set at the instant you started paginating. For example, given set
[a, b, c] when you start paginating, one item at a time, even if
you delete item c after you started reading the set, item c is returned.
The exception is if the history is no longer available for the deleted item
because history_days
is set to the default value of 0
or is less than the
minimum valid time needed. In that case, the deleted item is not returned with
the paginated results and an error is returned:
Requested timestamp <time> less than minimum allowed timestamp.
.
An after
cursor is valid for history_days
plus 15 minutes.
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!