2

I am trying to do a pagination with a Cosmos db but something was wrong with the skip command.

var resultDTO = this.client.CreateDocumentQuery<AuditDTO>(
             UriFactory.CreateDocumentCollectionUri(idDatabase, idCollection), queryOptions)

             .Skip(2*1)
             .Take(amount)
             .AsEnumerable()
             .ToList();

Do you know how to implement it?

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
CMorillo
  • 191
  • 1
  • 10

2 Answers2

4

Currently, the pagination supported and it is based on continuation token.

The following example illustrates a method that queries documents based on the desired page number, page size and continuation token:

private static async Task<KeyValuePair<string, IEnumerable<CeleryTask>>> QueryCosmosDBPage(int pageSize, string continuationToken)
{
    DocumentClient documentClient = new DocumentClient(new Uri("https://{CosmosDB/SQL Account Name}.documents.azure.com:443/"), "{CosmosDB/SQL Account Key}");

    var feedOptions = new FeedOptions {
        MaxItemCount = pageSize,
        EnableCrossPartitionQuery = true,

        // IMPORTANT: Set the continuation token (NULL for the first ever request/page)
        RequestContinuation = continuationToken 
    };

    IQueryable<CeleryTask> filter = documentClient.CreateDocumentQuery<CeleryTask>("dbs/{Database Name}/colls/{Collection Name}", feedOptions);
    IDocumentQuery<CeleryTask> query = filter.AsDocumentQuery();

    FeedResponse<CeleryTask> feedRespose = await query.ExecuteNextAsync<CeleryTask>();

    List<CeleryTask> documents = new List<CeleryTask>();
    foreach (CeleryTask t in feedRespose)
    {
        documents.Add(t);
    }
    return new KeyValuePair<string, IEnumerable<CeleryTask>>(feedRespose.ResponseContinuation, documents);
}
Sam Jones
  • 4,443
  • 2
  • 40
  • 45
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

CosmosDB does not have native support for skip take pagination yet. It is something the team is working on.

However there are ways to "cheat" it's behaviour.

You can use Cosmonaut which has skip-take pagination support using the .WithPagination(pageNum, pageSize) method. The way it achieves it is by going through the results till you get to the page, but there are ways to improve the performance.

You can read more about pagination and pagination recommendations here

Disclaimer: I am the creator of Cosmonaut

Nick Chapsas
  • 6,872
  • 1
  • 20
  • 29