In previous post, we have discussed about partitions. The purpose of creating partitions is to make the data retrieval process more effective. Designing partition wisely, by choosing an effective partition key is only one part of getting optimum data retrieval from Cosmos DB. The other part is to write queries that use the partitions effectively. In today’s post, we will discuss about querying a Cosmos DB container using the partition keys.
In-Partition Query
To optimize a query for a single partition, the query should have partition key specified. The query is routed to the specific physical partition which has been specified using the partition key value, in the query filter. Let’s look at an example query below:
SELECT * FROM c WHERE c.DeviceId = 'ADE-0001'
The above query specifies a partition key value ‘ADE-0001’ for the partition key (DeviceId) and therefore is directed to a specific physical partition containing the partition key value ADE-0001.
Cross-Partition Query
Now, lets have a look at an example of a cross-partition query:
SELECT * FROM c WHERE c.Location = 'Sydney'
The above query does not use the partition key (DeviceId) in the where clause and therefore the query will have to be directed to all the partitions, thereby taking longer to execute compared to the in-partition query. This results in running one query per physical partition in Cosmos DB.
Reference: https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-query-container