How to page a query in Azure Cosmos DB?

Asked

Viewed 112 times

4

I’m trying to pay for a consultation on Azure Cosmos DB, reading this post: Paging through query Results in Azure Documentdb, got to the code:

    public async Task <ICollection <TEntity>> GetAllPaged(int page, string colletionId) {
     FeedOptions queryOptions = new FeedOptions {
      MaxItemCount = 10
     };

     var query = client.CreateDocumentQuery <TEntity> (
       UriFactory.CreateDocumentCollectionUri(databaseId, colletionId), queryOptions)
      .AsDocumentQuery();

     FeedResponse <TEntity> result;
     List <TEntity> tEntitys = new List <TEntity> ();
     int interacoes = 0;
     while (query.HasMoreResults) {
      interacoes++;
      if (interacoes == page) {
       result = await query.ExecuteNextAsync <TEntity> ();
       tEntitys = result.ToList();
       break;
      }

     }
     return tEntitys;

    }

Explaining:

  • MaxItemCount = 10, total items per page.
  • while (query.HasMoreResults), perform a loop until there are results.
  • if (interacoes == page), when you get to my page I no longer need to check the next ones, where the break.

Problem:

Imagine that I have about 50002 documents, and that my page asks the method the result of number 5001, ie the last 2 records.

To each interaction of while that code:result = await query.ExecuteNextAsync<TEntity>() is responsible for each results page.

I thought to run this code only on the specific page I need through this code :if (interacoes == page), the problem of this is that only the first result is read, ie I need to read page by page to achieve the desired result described in the above scenario, and this has generated me 15 seconds of performance.

Note: Skip is not supported because it offers a bad performance. More Issues of the Github!

What can I do to make it better?

  • 5

    Is the question astronomy? : P :D

  • @Maniero gives a strength ai :)rs!

  • I don’t know about that :)

1 answer

1

Hello, maybe this library can help you Cosmonaut. It is specific to Cosmos DB and makes queries much easier, what you need is in the following implementation.

.WithPagination(int pageNumber, int pageSize)

It’s an extension of Iqueryable. on the github itself Cosmonaut you could find several usage examples.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.