Skip to content

Paging Azure Cosmos DB Query Results from .NET

Sponsor: Using RabbitMQ or Azure Service Bus in your .NET systems? Well, you could just use their SDKs and roll your own serialization, routing, outbox, retries, and telemetry. I mean, seriously, how hard could it be?

Learn more about Software Architecture & Design.
Join thousands of developers getting weekly updates to increase your understanding of software architecture and design concepts.


I received a comment on my Azure Cosmos DB Transactions from .NET post from Onur:
The thing I don’t like about Azure Cosmos DB is that it doesn’t support aggregations nor paging.
This was actually some pretty good timing of this comment as I just ran into a situation of a side project that required to page through  a result set.

Skip & Take

It does not appear that Azure Cosmos DB supports (yet) SKIP and TAKE, which you would expect to use in order to do paging.  Because of this, you can’t implement all the same functionality you might expect. But there is a a way to limit the number of records returned in a query and subsequently having the next query return the records were the previous query left off.  This means you can basically continue through your result set.

Continuations

Azure Cosmos DB has the concept of a continuationToken which is returned from a query which limits the number of records to return.  When using the CreateDocumentQuery<T> from the .NET SDK, you can specify an additional parameter for FeedOptions.

FeedOptions

Here’s an example of using FeedOptions to limit the number of results:

RequestContinuation

FeedOptions also property for specifying the RequestContinuation.  If you original query had a MaxItemCount and your query result exceeds the specified count, then your results will contain a ResponseContinuation property.
Combine these two to basically do forward paging.  Here is an xUnit test to outline:
   

Demo Source Code

I’ve put together a small .NET Core sample with an XUnit test from above. All the source code for this series is available on GitHub. Are you using Azure Cosmos DB? I’d love to hear your experiences so far along. Let me know on twitter or in the comments.