Navid Molavi
Navid Molavi

Reputation: 93

How to do run LINQ Count on a Cosmos-db query asynchronously on SDK V3

I have an existing Cosmos-db SDK V3 query in my C# code and I can run the Count method on it if "allowSynchronousQueryExecution" is set to true or GetItemsQueryIterator used to execute asynchronously. Is there any other way to run the Count asynchronously in a cleaner way like bellow:

var count = await query.CountAsync();

I know the SDK V2 is supporting the above code snippet.

Upvotes: 5

Views: 8778

Answers (3)

SteveA
SteveA

Reputation: 486

You can now use the code in your question, if you're using GetItemLinqQueryable();

Ensure you're including Microsoft.Azure.Cosmos.Linq in your using statements.

Example:

IOrderedQueryable<MyClass> linqQueryable = container.GetItemLinqQueryable<MyClass>();
int count = await linqQueryable.CountAsync();

If you wish to get the request charge and/or other details then use can use something like the following:

IOrderedQueryable<MyClass> linqQueryable = container.GetItemLinqQueryable<MyClass>();
Response<int> count = await linqQueryable.CountAsync();
var charge = count.RequestCharge;

See: https://github.com/Azure/azure-cosmos-dotnet-v3/pull/729 and https://github.com/Azure/azure-cosmos-dotnet-v3/pull/776 for details

Upvotes: 9

Sajeetharan
Sajeetharan

Reputation: 222582

Here is one of the sample function I used with SDK V3,

public async Task<T> GetByIdAsync(string id, object partitionKeyValue = null)
        {
            var options = this.EnsureRequestOptions(partitionKeyValue);

            var sqlQuery = new QueryDefinition($"select * from {this.containerName} c where c.id = @id").WithParameter("@id", id);
            var iterator = this.container.GetItemQueryIterator<T>(
                sqlQuery,
                requestOptions: options);

            while (iterator.HasMoreResults)
            {
                var response = await iterator.ReadNextAsync().AnyContext();
                this.LogRequestCharge(response.RequestCharge, response.ActivityId);

                foreach (var result in response.Resource)
                {
                    return result;
                }
            }

Upvotes: 0

Ste Pammenter
Ste Pammenter

Reputation: 3148

For anyone who stumbles on this, in SDK V3 you can do the following:

var query = this.container.GetItemLinqQueryable<T>(
         requestOptions: new QueryRequestOptions
         {
             PartitionKey = new PartitionKey(yourKey),
             MaxItemCount = maxCount
         }
     )
     .Where(yourPredicate);

 var feedIterator = this.container.GetItemQueryIterator<T>(query.ToQueryDefinition());

 var results = new List<T>();
 while (feedIterator.HasMoreResults)
 {
   results.AddRange(await feedIterator.ReadNextAsync());
 }

Upvotes: 7

Related Questions