Azure DocumentDB has built in support for paging, but it's not immediately clear from the documentation how. It has supported the TOP
operator for a while, but SKIP
is not supported at the moment.
Today we'll see how to page through query results.
Paging through query results in a loop
The first scenario is paging through the results of a query in a loop. To do this we need to use the MaxItemCount
property of the FeedOptions
:
var endpoint = "document db url";
var primaryKey = "document db key";
var client = new DocumentClient(new Uri(endpoint), primaryKey);
var collection = UriFactory.CreateDocumentCollectionUri("database id", "collection id");
var options = new FeedOptions
{
MaxItemCount = 100
};
var query = client.CreateDocumentQuery<Document>(collection, options).AsDocumentQuery();
while (query.HasMoreResults)
{
var result = await query.ExecuteNextAsync<Document>();
// Process paged results
}
The important parts of this code are:
- Pass in a
FeedOptions
instance to theCreateDocumentQuery()
method with theMaxItemCount
property set. This will be the page size. - Use the
AsDocumentQuery()
extension method to cast theIOrderedQueryable
query to anIDocumentQuery
. - Use the
HasMoreResults
property to loop over the paged query results. - Use the
ExecuteNextAsync()
to get each page of results.
Getting the next page of results from a query executed earlier
In many apps we need to get our query results one page at a time. To support this DocumentDB uses the concept of a continuation token. The continuation token is used behind the scenes by the SDK in the example above. In this example we will use it directly.
The first step is to capture and save the continuation token for later:
var continuationToken = result.ResponseContinuation;
Once we have the continuation token, we can use it to get the next page of results:
var endpoint = "document db url";
var primaryKey = "document db key";
var client = new DocumentClient(new Uri(endpoint), primaryKey);
var collection = UriFactory.CreateDocumentCollectionUri("database id", "collection id");
var options = new FeedOptions
{
MaxItemCount = 100,
RequestContinuation = "continuation token"
};
var query = client.CreateDocumentQuery<Document>(collection, options).AsDocumentQuery();
var result = await query.ExecuteNextAsync<Document>();
// Process paged results
The important part of this code is using the RequestContinuation
property of the FeedOptions
.
References
- https://azure.microsoft.com/en-gb/documentation/services/documentdb
- https://azure.microsoft.com/en-gb/blog/documentdb-paging-support-with-top-and-more-query-improvements
- https://feedback.azure.com/forums/263030-documentdb/suggestions/6350987--documentdb-allow-paging-skip-take
- https://github.com/Azure/azure-documentdb-dotnet/blob/master/samples/code-samples/Queries/Program.cs#L604-L663