Skip to content

Continuation Example

Chris Dahlberg edited this page Mar 19, 2019 · 1 revision

An aggregate query can be executed incrementally, for example to reduce RU demand or to return paged results to a client. This is done using a continuation token and, optionally, by specifying the page size.

CosmosContainer container = {{your_target_container}};

// Get the first page of results
var queryOptions = new AggregateQueryOptions { PartitionKey = "13", MaxItemCount = 10 };
var query = container.CreateAggregateDocumentQuery<Sale>(queryOptions)
    .Aggregate((aggregate, current) => new Sale { Amount = aggregate.Amount + current.Amount })
    .AsDocumentQuery();

string continuationToken = null;

var results = new List<Sale>();

while (query.HasMoreResults)
{
    var resultsPage = await query.ExecuteNextAsync(cancellationToken).ConfigureAwait(false);
    results.AddRange(resultsPage);

    continuationToken = resultsPage.ResponseContinuation;
}

// Get the next page of results
queryOptions.RequestContinuation = continuationToken;
query = container.CreateAggregateDocumentQuery<Sale>(queryOptions)
    .Aggregate((aggregate, current) => new Sale { Amount = aggregate.Amount + current.Amount })
    .AsDocumentQuery();

while (query.HasMoreResults)
{
    var resultsPage = await query.ExecuteNextAsync(cancellationToken).ConfigureAwait(false);
    results.AddRange(resultsPage);
}
Clone this wiki locally