Search code examples
azure-cosmosdb

Cosmos DB Pagination - Total records


We're showing data from a CosmosDb in a table with pagination. The underlying query is using grouping along with OFFSET and LIMIT.

We would need to know the total number of rows or total number of pages in order to display page numbers and "Go to last". Is this possible?

PS. When running the query in Azure Data explorer, I can see Output document count which seams to be what I'm looking for. Is it possible to get this value using GetItemQueryIterator?


Solution

  • The FeedResponse has QueryMetrics available through feedResponse.Diagnostics.GetQueryMetrics(). This metric object has a OutputDocumentCount which seams to correlate to the number of documents in the context of the query (w/o OFFSET and LIMIT)

    long totalCount = 0;
    var data = new List<JObject>();
    using (FeedIterator<JObject> resultSetIterator = _container.GetItemQueryIterator<JObject>(queryDefinition))
    {
        while (resultSetIterator.HasMoreResults)
        {
            FeedResponse<JObject> response = await resultSetIterator.ReadNextAsync();
            data.AddRange(response);
            var metrics = response.Diagnostics.GetQueryMetrics();
            if (metrics != null)
                totalCount = metrics.CumulativeMetrics.OutputDocumentCount; // Here it is ;)
    
        }
    }