Horsing around the CosmosDB .NET SDK, I found an intriguing issue. I wanted to use the SDK LINQ support for the following query:
SELECT VALUE COUNT(1) FROM c WHERE <predicate>
Well, immediately after writing the LINQ query, I realized there might be no way to handle such queries as document queries. However, since document queries allow you to capture query metrics and unblock a thread between pages of results, I strongly prefer it. Here's the code:
client.CreateDocumentQuery<TEntity>.Where(<predicate>).Count()
Even though I understand that the result type of Count() isn't IQueryable, is there a way to handle "count" queries as document queries?
Of course there is a way to do that.
There is a CountAsync
extension built into the SDK.
Simply construct your IQueryable
and use .CountAsync()
when you are ready to get the count.
Keep in mind however that there will be no metric collection as the result is aggregated in the SDK.
If you really need metrics then you can use the usual DocumentQuery
created from SQL rather than LINQ and the while.HasMoreResults
, ExecuteNextAsync
logic and capture the metrics from the paginated result, per iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With