简体   繁体   中英

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. 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.

a)

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

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?!

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.

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 .

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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