简体   繁体   English

Azure Cosmos DB - 为查询提供分区键的方式有何不同?

[英]Azure Cosmos DB - difference in how the partition key is supplied to query?

I am querying a Cosmos DB collection from my .NET Core app.我正在从我的 .NET Core 应用程序查询 Cosmos DB 集合。 Now I am wondering, if there is any difference (ie: better to do it one way vs the other) in how I supply the partition key to a query?现在我想知道,我如何向查询提供分区键是否有任何区别(即:最好以一种方式与另一种方式进行)?

Below, region is my partition key.下面, region是我的分区键。

a)一种)

var queryString = $"SELECT TOP 100 * FROM c WHERE c.region ='{region}'";
var query = this.container.GetItemQueryIterator<Item>(new QueryDefinition(queryString));

b) b)

var queryString = "SELECT TOP 100 * FROM c";
var query = this.container.GetItemQueryIterator<Item>(new QueryDefinition(queryString), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(region) });

At least the RU (request units) seem to be the same, so maybe Cosmos DB internally optimizes the query anyway and rewrites a) to b) or vice versa?!至少 RU(请求单元)似乎是相同的,所以也许 Cosmos DB 内部无论如何都会优化查询并将 a) 重写为 b),反之亦然?!

When you specify a partition key as part of your query, Cosmos will route the query to the specified partition, which results in more efficient execution.当您将分区键指定为查询的一部分时,Cosmos 会将查询路由到指定的分区,从而提高执行效率。

You can specify the partition key in the two ways you show in your question, either by adding it to the WHERE clause as described in this article , or you can explicitly specify the partition key using the QueryRequestOptions .你可以在你在你的问题表明这两种方式将其添加到WHERE子句指定分区键,无论是在这篇文章中描述的,或可以明确指定使用分区键QueryRequestOptions

Behind the scenes both of these will be handled the same way by the database engine and the query will execute against directly against the partition you specified, so the RU cost should be similar for both.在后台,数据库引擎将以相同的方式处理这两者,并且查询将直接针对您指定的分区执行,因此两者的 RU 成本应该相似。

The only real difference is that in some cases the client SDK for the API you are using may require you to either specify the partition key using QueryRequestOptions or enable cross partition query using the relevant property.唯一真正的区别是,在某些情况下,您使用的 API 的客户端 SDK 可能要求您使用 QueryRequestOptions 指定分区键或使用相关属性启用跨分区查询。 In this case you definitely want to specify the partition key for performance reasons.在这种情况下,出于性能原因,您肯定要指定分区键。

Yes there is a difference.是,有一点不同。

As per the documentation and best practices, 2nd one is the most preferred way of writing the query since the CosmosDB SDK itself is aware of the partition key while the first one tends to create the cross partition which is not necessary.根据文档和最佳实践,第二个是编写查询的首选方式,因为 CosmosDB SDK 本身知道分区键,而第一个倾向于创建不必要的交叉分区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM