在 Azure Cosmos DB 中查找请求单位费用Find the request unit charge in Azure Cosmos DB

本文介绍如何通过不同的方式,来查找针对 Azure Cosmos DB 中的容器执行的任何操作所消耗的请求单位 (RU)。This article presents the different ways you can find the request unit (RU) consumption for any operation executed against a container in Azure Cosmos DB. 目前,若要度量这种消耗,只能使用 Azure 门户,或者通过某个 SDK 检查 Azure Cosmos DB 发回的响应。Currently, you can measure this consumption only by using the Azure portal or by inspecting the response sent back from Azure Cosmos DB through one of the SDKs.

SQL(核心)APISQL (Core) API

如果使用 SQL API,则可以使用多个选项来查找针对 Azure Cosmos 容器执行的操作所消耗的 RU。If you're using the SQL API, you have multiple options for finding the RU consumption for an operation against an Azure Cosmos container.

使用 Azure 门户Use the Azure portal

目前,在 Azure 门户中只能查找 SQL 查询的请求费用。Currently, you can find the request charge in the Azure portal only for a SQL query.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 创建新的 Azure Cosmos 帐户并在其中植入数据,或选择一个已包含数据的现有 Azure Cosmos 帐户。Create a new Azure Cosmos account and feed it with data, or select an existing Azure Cosmos account that already contains data.

  3. 转到“数据资源管理器”窗格,然后选择要处理的容器。 Go to the Data Explorer pane, and then select the container you want to work on.

  4. 选择“新建 SQL 查询”。 Select New SQL Query.

  5. 输入有效的查询,然后选择“执行查询” 。Enter a valid query, and then select Execute Query.

  6. 选择“查询统计信息”,以显示执行的请求的实际请求费用。 Select Query Stats to display the actual request charge for the request you executed.

    Azure 门户中的 SQL 查询请求费用屏幕截图

使用 .NET SDKUse the .NET SDK

.NET V2 SDK.NET V2 SDK

.NET SDK v2 返回的对象公开 RequestCharge 属性:Objects that are returned from the .NET SDK v2 expose a RequestCharge property:

ResourceResponse<Document> fetchDocumentResponse = await client.ReadDocumentAsync(
    UriFactory.CreateDocumentUri("database", "container", "itemId"),
    new RequestOptions
    {
        PartitionKey = new PartitionKey("partitionKey")
    });
var requestCharge = fetchDocumentResponse.RequestCharge;

StoredProcedureResponse<string> storedProcedureCallResponse = await client.ExecuteStoredProcedureAsync<string>(
    UriFactory.CreateStoredProcedureUri("database", "container", "storedProcedureId"),
    new RequestOptions
    {
        PartitionKey = new PartitionKey("partitionKey")
    });
requestCharge = storedProcedureCallResponse.RequestCharge;

IDocumentQuery<dynamic> query = client.CreateDocumentQuery(
    UriFactory.CreateDocumentCollectionUri("database", "container"),
    "SELECT * FROM c",
    new FeedOptions
    {
        PartitionKey = new PartitionKey("partitionKey")
    }).AsDocumentQuery();
while (query.HasMoreResults)
{
    FeedResponse<dynamic> queryResponse = await query.ExecuteNextAsync<dynamic>();
    requestCharge = queryResponse.RequestCharge;
}

.NET V3 SDK.NET V3 SDK

.NET SDK v3 返回的对象公开 RequestCharge 属性:Objects that are returned from the .NET SDK v3 expose a RequestCharge property:

Container container = this.cosmosClient.GetContainer("database", "container");
string itemId = "myItem";
string partitionKey = "partitionKey";
string storedProcedureId = "storedProcedureId";
string queryText = "SELECT * FROM c";

ItemResponse<dynamic> itemResponse = await container.CreateItemAsync<dynamic>(
    item: new { id = itemId, pk = partitionKey },
    partitionKey: new PartitionKey(partitionKey));
double requestCharge = itemResponse.RequestCharge;

Scripts scripts = container.Scripts;
StoredProcedureExecuteResponse<object> sprocResponse = await scripts.ExecuteStoredProcedureAsync<object>(
    storedProcedureId: storedProcedureId,
    partitionKey: new PartitionKey(partitionKey),
    parameters: new dynamic[] { new object() });

requestCharge = sprocResponse.RequestCharge;

FeedIterator<dynamic> feedIterator = container.GetItemQueryIterator<dynamic>(
     queryText: queryText,
     requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(partitionKey) });
while (feedIterator.HasMoreResults)
{
    FeedResponse<dynamic> feedResponse = await feedIterator.ReadNextAsync();
    requestCharge = feedResponse.RequestCharge;
}

有关详细信息,请参阅快速入门:在 Azure Cosmos DB 中使用 SQL API 帐户生成 .NET Web 应用For more information, see Quickstart: Build a .NET web app by using a SQL API account in Azure Cosmos DB.

使用 Java SDKUse the Java SDK

Java SDK 返回的对象公开 getRequestCharge() 方法:Objects that are returned from the Java SDK expose a getRequestCharge() method:

RequestOptions requestOptions = new RequestOptions();
requestOptions.setPartitionKey(new PartitionKey("partitionKey"));

Observable<ResourceResponse<Document>> readDocumentResponse = client.readDocument(String.format("/dbs/%s/colls/%s/docs/%s", "database", "container", "itemId"), requestOptions);
readDocumentResponse.subscribe(result -> {
    double requestCharge = result.getRequestCharge();
});

Observable<StoredProcedureResponse> storedProcedureResponse = client.executeStoredProcedure(String.format("/dbs/%s/colls/%s/sprocs/%s", "database", "container", "storedProcedureId"), requestOptions, null);
storedProcedureResponse.subscribe(result -> {
    double requestCharge = result.getRequestCharge();
});

FeedOptions feedOptions = new FeedOptions();
feedOptions.setPartitionKey(new PartitionKey("partitionKey"));

Observable<FeedResponse<Document>> feedResponse = client
    .queryDocuments(String.format("/dbs/%s/colls/%s", "database", "container"), "SELECT * FROM c", feedOptions);
feedResponse.forEach(result -> {
    double requestCharge = result.getRequestCharge();
});

有关详细信息,请参阅快速入门:使用 Azure Cosmos DB SQL API 帐户生成 Java 应用程序For more information, see Quickstart: Build a Java application by using an Azure Cosmos DB SQL API account.

使用 Node.js SDKUse the Node.js SDK

Node.js SDK 返回的对象公开 headers 子对象,该对象可映射底层 HTTP API 返回的所有标头。Objects that are returned from the Node.js SDK expose a headers subobject that maps all the headers returned by the underlying HTTP API. 请求费用显示在 x-ms-request-charge 键下:The request charge is available under the x-ms-request-charge key:

const item = await client
    .database('database')
    .container('container')
    .item('itemId', 'partitionKey')
    .read();
var requestCharge = item.headers['x-ms-request-charge'];

const storedProcedureResult = await client
    .database('database')
    .container('container')
    .storedProcedure('storedProcedureId')
    .execute({
        partitionKey: 'partitionKey'
    });
requestCharge = storedProcedureResult.headers['x-ms-request-charge'];

const query = client.database('database')
    .container('container')
    .items
    .query('SELECT * FROM c', {
        partitionKey: 'partitionKey'
    });
while (query.hasMoreResults()) {
    var result = await query.executeNext();
    requestCharge = result.headers['x-ms-request-charge'];
}

有关详细信息,请参阅快速入门:使用 Azure Cosmos DB SQL API 帐户生成 Node.js 应用For more information, see Quickstart: Build a Node.js app by using an Azure Cosmos DB SQL API account.

使用 Python SDKUse the Python SDK

Python SDK 返回的 CosmosClient 对象公开 last_response_headers 字典,该字典可映射底层 HTTP API 针对上次执行的操作返回的所有标头。The CosmosClient object from the Python SDK exposes a last_response_headers dictionary that maps all the headers returned by the underlying HTTP API for the last operation executed. 请求费用显示在 x-ms-request-charge 键下:The request charge is available under the x-ms-request-charge key:

response = client.ReadItem(
    'dbs/database/colls/container/docs/itemId', {'partitionKey': 'partitionKey'})
request_charge = client.last_response_headers['x-ms-request-charge']

response = client.ExecuteStoredProcedure(
    'dbs/database/colls/container/sprocs/storedProcedureId', None, {'partitionKey': 'partitionKey'})
request_charge = client.last_response_headers['x-ms-request-charge']

有关详细信息,请参阅快速入门:使用 Azure Cosmos DB SQL API 帐户生成 Python 应用For more information, see Quickstart: Build a Python app by using an Azure Cosmos DB SQL API account.

用于 MongoDB 的 Azure Cosmos DB APIAzure Cosmos DB API for MongoDB

RU 费用由名为 getLastRequestStatistics 的自定义数据库命令公开。The RU charge is exposed by a custom database command named getLastRequestStatistics. 该命令返回一个文档,其中包含上次执行的操作的名称、其请求费用和持续时间。The command returns a document that contains the name of the last operation executed, its request charge, and its duration. 如果使用 Azure Cosmos DB API for MongoDB,则可以通过多个选项来检索 RU 费用。If you use the Azure Cosmos DB API for MongoDB, you have multiple options for retrieving the RU charge.

使用 Azure 门户Use the Azure portal

目前,在 Azure 门户中只能查找查询的请求费用。Currently, you can find the request charge in the Azure portal only for a query.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 创建新的 Azure Cosmos 帐户并在其中植入数据,或选择一个已包含数据的现有帐户。Create a new Azure Cosmos account and feed it with data, or select an existing account that already contains data.

  3. 转到“数据资源管理器”窗格,然后选择要处理的容器。 Go to the Data Explorer pane, and then select the container you want to work on.

  4. 选择“新建查询” 。Select New Query.

  5. 输入有效的查询,然后选择“执行查询” 。Enter a valid query, and then select Execute Query.

  6. 选择“查询统计信息”,以显示执行的请求的实际请求费用。 Select Query Stats to display the actual request charge for the request you executed.

    Azure 门户中的 MongoDB 查询请求费用屏幕截图

使用 MongoDB .NET 驱动程序Use the MongoDB .NET driver

使用官方 MongoDB .NET 驱动程序时,可以通过对 IMongoDatabase 对象调用 RunCommand 方法来执行命令。When you use the official MongoDB .NET driver, you can execute commands by calling the RunCommand method on a IMongoDatabase object. 此方法需要 Command<> 抽象类的实现:This method requires an implementation of the Command<> abstract class:

class GetLastRequestStatisticsCommand : Command<Dictionary<string, object>>
{
    public override RenderedCommand<Dictionary<string, object>> Render(IBsonSerializerRegistry serializerRegistry)
    {
        return new RenderedCommand<Dictionary<string, object>>(new BsonDocument("getLastRequestStatistics", 1), serializerRegistry.GetSerializer<Dictionary<string, object>>());
    }
}

Dictionary<string, object> stats = database.RunCommand(new GetLastRequestStatisticsCommand());
double requestCharge = (double)stats["RequestCharge"];

有关详细信息,请参阅快速入门:使用 Azure Cosmos DB API for MongoDB 生成 .NET Web 应用For more information, see Quickstart: Build a .NET web app by using an Azure Cosmos DB API for MongoDB.

使用 MongoDB Java 驱动程序Use the MongoDB Java driver

使用官方 MongoDB Java 驱动程序时,可以通过对 MongoDatabase 对象调用 runCommand 方法来执行命令:When you use the official MongoDB Java driver, you can execute commands by calling the runCommand method on a MongoDatabase object:

Document stats = database.runCommand(new Document("getLastRequestStatistics", 1));
Double requestCharge = stats.getDouble("RequestCharge");

有关详细信息,请参阅快速入门:使用 Azure Cosmos DB API for MongoDB 和 Java SDK 生成 Web 应用For more information, see Quickstart: Build a web app by using the Azure Cosmos DB API for MongoDB and the Java SDK.

使用 MongoDB Node.js 驱动程序Use the MongoDB Node.js driver

使用官方 MongoDB Node.js 驱动程序时,可以通过对 db 对象调用 command 方法来执行命令:When you use the official MongoDB Node.js driver, you can execute commands by calling the command method on a db object:

db.command({ getLastRequestStatistics: 1 }, function(err, result) {
    assert.equal(err, null);
    const requestCharge = result['RequestCharge'];
});

有关详细信息,请参阅快速入门:将现有的 MongoDB Node.js Web 应用迁移到 Azure Cosmos DBFor more information, see Quickstart: Migrate an existing MongoDB Node.js web app to Azure Cosmos DB.

Cassandra APICassandra API

针对 Azure Cosmos DB Cassandra API 执行操作时,RU 费用将在传入的有效负载中以名为 RequestCharge 的字段形式返回。When you perform operations against the Azure Cosmos DB Cassandra API, the RU charge is returned in the incoming payload as a field named RequestCharge. 可以使用多个选项来检索 RU 费用。You have multiple options for retrieving the RU charge.

使用 .NET SDKUse the .NET SDK

使用 .NET SDK 时,可以在 RowSet 对象的 Info 属性下检索传入的有效负载:When you use the .NET SDK, you can retrieve the incoming payload under the Info property of a RowSet object:

RowSet rowSet = session.Execute("SELECT table_name FROM system_schema.tables;");
double requestCharge = BitConverter.ToDouble(rowSet.Info.IncomingPayload["RequestCharge"].Reverse().ToArray(), 0);

有关详细信息,请参阅快速入门:使用 .NET SDK 和 Azure Cosmos DB 生成 Cassandra 应用For more information, see Quickstart: Build a Cassandra app by using the .NET SDK and Azure Cosmos DB.

使用 Java SDKUse the Java SDK

使用 Java SDK 时,可以通过对 ResultSet 对象调用 getExecutionInfo() 方法来检索传入的有效负载:When you use the Java SDK, you can retrieve the incoming payload by calling the getExecutionInfo() method on a ResultSet object:

ResultSet resultSet = session.execute("SELECT table_name FROM system_schema.tables;");
Double requestCharge = resultSet.getExecutionInfo().getIncomingPayload().get("RequestCharge").getDouble();

有关详细信息,请参阅快速入门:使用 Java SDK 和 Azure Cosmos DB 生成 Cassandra 应用For more information, see Quickstart: Build a Cassandra app by using the Java SDK and Azure Cosmos DB.

Gremlin APIGremlin API

使用 Gremlin API 时,可以通过多个选项来查找针对 Azure Cosmos 容器执行的操作所消耗的 RU。When you use the Gremlin API, you have multiple options for finding the RU consumption for an operation against an Azure Cosmos container.

使用驱动程序和 SDKUse drivers and SDK

Gremlin API 返回的标头将映射到目前由 Gremlin .NET 和 Java SDK 公开的自定义状态特性。Headers returned by the Gremlin API are mapped to custom status attributes, which currently are surfaced by the Gremlin .NET and Java SDK. 请求费用显示在 x-ms-request-charge 键下。The request charge is available under the x-ms-request-charge key.

使用 .NET SDKUse the .NET SDK

使用 Gremlin .NET SDK 时,状态特性将显示在 ResultSet<> 对象的 StatusAttributes 属性下:When you use the Gremlin.NET SDK, status attributes are available under the StatusAttributes property of the ResultSet<> object:

ResultSet<dynamic> results = client.SubmitAsync<dynamic>("g.V().count()").Result;
double requestCharge = (double)results.StatusAttributes["x-ms-request-charge"];

有关详细信息,请参阅快速入门:使用 Azure Cosmos DB Gremlin API 帐户生成 .NET Framework 或 Core 应用程序For more information, see Quickstart: Build a .NET Framework or Core application by using an Azure Cosmos DB Gremlin API account.

使用 Java SDKUse the Java SDK

使用 Gremlin Java SDK 时,可以通过对 ResultSet 对象调用 statusAttributes() 方法来检索状态特性:When you use the Gremlin Java SDK, you can retrieve status attributes by calling the statusAttributes() method on the ResultSet object:

ResultSet results = client.submit("g.V().count()");
Double requestCharge = (Double)results.statusAttributes().get().get("x-ms-request-charge");

有关详细信息,请参阅快速入门:使用 Java SDK 在 Azure Cosmos DB 中创建图形数据库For more information, see Quickstart: Create a graph database in Azure Cosmos DB by using the Java SDK.

表 APITable API

目前,唯一能够返回表操作 RU 费用的 SDK 是 .NET 标准 SDKCurrently, the only SDK that returns the RU charge for table operations is the .NET Standard SDK. TableResult 对象公开 RequestCharge 属性,针对 Azure Cosmos DB 表 API 使用该 SDK 时,该 SDK 会填充该属性:The TableResult object exposes a RequestCharge property that is populated by the SDK when you use it against the Azure Cosmos DB Table API:

CloudTable tableReference = client.GetTableReference("table");
TableResult tableResult = tableReference.Execute(TableOperation.Insert(new DynamicTableEntity("partitionKey", "rowKey")));
if (tableResult.RequestCharge.HasValue) // would be false when using Azure Storage Tables
{
    double requestCharge = tableResult.RequestCharge.Value;
}

有关详细信息,请参阅快速入门:使用 .NET SDK 和 Azure Cosmos DB 生成表 API 应用For more information, see Quickstart: Build a Table API app by using the .NET SDK and Azure Cosmos DB.

后续步骤Next steps

若要了解如何优化 RU 消耗量,请参阅以下文章:To learn about optimizing your RU consumption, see these articles: