首页 > 解决方案 > 在 CosmosClient 中使用 LINQ 查询时查找 RequestCharge

问题描述

当我使用CreateItemAsync然后我得到一个ItemResponse它允许我访问RequestChargeRU 并可能记录它,这样我就可以准确地了解我对 RU 的使用。

但是,当使用 LINQ 使用 CosmosClient 进行查询时,我看不到任何获取 RequestCharge 的方法。看到 RequestCharge 非常有用,但它似乎只有在我以某种方式查询时才可用,所以我认为我一定遗漏了一些东西。

这是我的代码示例。

var tenantContainer = cosmos.GetContainer("myapp", "tenant");
var query = tenantContainer.GetItemLinqQueryable<Tenant>(true, null, 
    new QueryRequestOptions { PartitionKey = new PartitionKey("all") })
    .Where(r => r.AccountId = "1234");

var tenants = query.ToList();
//track.Metric("GetTenants", cosmosResponse.RequestCharge);

请注意,我使用的是“新”CosmosClient而不是旧的DocumentClient.

标签: c#azure-cosmosdb

解决方案


确保包含此 using 语句。

using Microsoft.Azure.Cosmos.Linq;

然后你可以使用.ToFeedIterator()which contains a property with RequestCharge

这是完整的代码示例:

var container = _cosmos.GetContainer("mydb", "user");

// Normal linq query
var query = container.GetItemLinqQueryable<Shared.Models.User>(true, null,
    new QueryRequestOptions { PartitionKey = new PartitionKey(tenantName) })
    .Where(r => r.Email == loginRequest.Email);

// Instead of getting the result, first convert to feed iterator
var iterator = query.ToFeedIterator();

// And finally execute with this command that also supports paging
var cosmosResponse = await iterator.ReadNextAsync();

// And then the RequestCharge is readily available
_track.Metric("GetUserForAuthentication", cosmosResponse.RequestCharge);

// And whatever linq execution you wanted to do, you can do on the response
var user = cosmosResponse.FirstOrDefault();

推荐阅读