Skip to main content

How to Query the Items of One Partition in Azure Cosmos DB with C#

· 12 min read
Jagdish Kumawat
Founder @ Dewiride

An Azure Cosmos DB query from C# stays in one partition when you give it that partition's key, in QueryRequestOptions or as a filter on the partition key's property. Leave both out, and SELECT * FROM c returns the items of every partition. Here are all three, run against a small container, with what each returned and what it cost.

A Cosmos DB for NoSQL container groups its items by a partition key: a property, named by the container's partition key path, such as /listId. All items with the same value form one logical partition. Reading one user's data, one tenant's data or one list's items usually means reading one logical partition, and that's what this post shows.

Syntax​

The partition key in the request options:

Syntax
using FeedIterator<<Type>> <feed> = <container>.GetItemQueryIterator<<Type>>(
new QueryDefinition("<query>"),
requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("<value>") });

while (<feed>.HasMoreResults)
{
FeedResponse<<Type>> <page> = await <feed>.ReadNextAsync();
// use the items in <page>, and <page>.RequestCharge
}

Or a filter on the partition key's property in the query itself:

Syntax
QueryDefinition <query> = new QueryDefinition("SELECT * FROM c WHERE c.<partition-key-property> = @<parameter>")
.WithParameter("@<parameter>", "<value>");
PartWhat it is
<Type>The C# type each item is read into
<container>The Container from CosmosClient.GetContainer
<query>The query, in Cosmos DB's SQL, such as SELECT * FROM c
QueryRequestOptions.PartitionKeyThe reference: gets or sets the PartitionKey for the current request. The query runs in that logical partition only
<value>The partition key value of the partition to read, such as home
<feed>.HasMoreResultsTells if there is more results that need to be retrieved from the service. Results come a page at a time
<page>.RequestChargeThe request units the page cost
<partition-key-property>The property the container's partition key path names, such as listId for /listId
@<parameter>A query parameter. WithParameter fills it in, so the value never becomes part of the query text

Microsoft's article on querying containers explains the filter form: if the query has a partition key filter specified, Azure Cosmos DB automatically optimizes the query. It routes the query to the physical partitions corresponding to the partition key values specified in the filter.

The Example​

A small to-do app keeps its items in a container howto-todos, whose partition key path is /listId. There are three lists, home, work and groceries, so the container has three logical partitions. The console app TodoQuery adds seven items, then runs three queries: one with the partition key in the options, one without it, and one with a filter on listId. It signs in with my Azure CLI account.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.
  • The Azure CLI, signed in with az login. The app uses that sign-in.
  • A Cosmos DB for NoSQL container whose partition key path is /listId, and a Cosmos DB data role for your account on it, such as Cosmos DB Built-in Data Contributor. An Azure role such as Owner isn't enough: Connect using role-based access control and Microsoft Entra ID.

Step 1: Create a Console App and Add the Packages​

Terminal
dotnet new console -n TodoQuery
cd TodoQuery
dotnet add package Microsoft.Azure.Cosmos --version 3.64.0
dotnet add package Newtonsoft.Json --version 13.0.4
dotnet add package Azure.Identity --version 1.21.0

dotnet new console creates the project, and each dotnet add package adds one package and ends with lines like these:

Output (the last lines of the last command)
info : PackageReference for package 'Azure.Identity' version '1.21.0' added to file '/Users/you/source/TodoQuery/TodoQuery.csproj'.
log : Restored /Users/you/source/TodoQuery/TodoQuery.csproj (in 702 ms).

Microsoft.Azure.Cosmos is the Cosmos DB SDK, Newtonsoft.Json is a package the SDK requires you to reference yourself, and Azure.Identity has the Microsoft Entra ID credentials. How to Connect to Azure Cosmos DB with Microsoft Entra ID in C# explains each one and the client in detail.

Step 2: Connect and Add the Items​

Replace Program.cs with the client and the items:

Program.cs (the client and the items)
using System.Text.Json;
using Azure.Identity;
using Microsoft.Azure.Cosmos;

// The account's URI, from its Overview page in the Azure portal.
const string AccountEndpoint = "https://cosmos-maf-servicedesk-4224.documents.azure.com:443/";

using CosmosClient client = new(AccountEndpoint, new AzureCliCredential(), new CosmosClientOptions
{
UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Web,
});
Container todos = client.GetContainer("servicedesk", "howto-todos");

// Three to-do lists. Each list is one partition, because the container's partition key path is /listId.
// Upsert, so running the app again doesn't add the items twice.
TodoItem[] items =
[
new("1", "home", "Water the plants"),
new("2", "home", "Pay the electricity bill"),
new("3", "work", "Send the weekly report"),
new("4", "work", "Book a meeting room"),
new("5", "groceries", "Milk"),
new("6", "groceries", "Bread"),
new("7", "groceries", "Coffee"),
];
foreach (TodoItem item in items)
{
await todos.UpsertItemAsync(item, new PartitionKey(item.ListId));
}
  • AccountEndpoint is your account's URI, from its Overview page in the Azure portal.
  • JsonSerializerOptions.Web writes property names in camelCase, so ListId becomes listId, the property the partition key path /listId names, and Id becomes id, the name Cosmos DB requires.
  • UpsertItemAsync creates each item or replaces it, so running the app twice doesn't add anything twice.

Step 3: Query One Partition with the Partition Key​

Program.cs (the first query)
QueryDefinition everything = new("SELECT * FROM c");

// 1. In the home list's partition only: the partition key is set in the request options.
await RunQueryAsync("With the partition key", everything, new QueryRequestOptions { PartitionKey = new PartitionKey("home") });

SELECT * FROM c has no filter at all. The partition key in QueryRequestOptions is what keeps it inside the home list.

RunQueryAsync, at the end of the file, reads every page of results, adds up RequestCharge and prints what came back:

Program.cs (reading the results)
async Task RunQueryAsync(string label, QueryDefinition query, QueryRequestOptions options)
{
using FeedIterator<TodoItem> feed = todos.GetItemQueryIterator<TodoItem>(query, requestOptions: options);

List<TodoItem> found = [];
double charge = 0;
while (feed.HasMoreResults)
{
FeedResponse<TodoItem> page = await feed.ReadNextAsync();
charge += page.RequestCharge;
found.AddRange(page);
}

Console.WriteLine($"{label}: {found.Count} items, {charge} RU");
foreach (TodoItem item in found)
{
Console.WriteLine($" {item.ListId}: {item.Title}");
}
}

Step 4: Run the Same Query Without a Partition Key​

Program.cs (the second query)
// 2. The same query without a partition key: every partition.
await RunQueryAsync("Without the partition key", everything, new QueryRequestOptions());

Same query text, but no partition key: nothing keeps it in one list.

Step 5: Filter on the Partition Key's Property​

Program.cs (the third query)
// 3. A filter on the partition key's property: Cosmos DB routes the query to that partition by itself.
QueryDefinition homeOnly = new QueryDefinition("SELECT * FROM c WHERE c.listId = @listId")
.WithParameter("@listId", "home");
await RunQueryAsync("With a filter on listId", homeOnly, new QueryRequestOptions());

No partition key in the options this time, but the query filters on listId with =, and Cosmos DB routes it to that partition by itself.

Step 6: Run It​

Terminal
dotnet run
Output
With the partition key: 2 items, 2.84 RU
home: Water the plants
home: Pay the electricity bill
Without the partition key: 7 items, 2.34 RU
home: Water the plants
home: Pay the electricity bill
work: Send the weekly report
work: Book a meeting room
groceries: Milk
groceries: Bread
groceries: Coffee
With a filter on listId: 2 items, 2.84 RU
home: Water the plants
home: Pay the electricity bill

macOS-style terminal window titled Terminal — TodoQuery showing dotnet run: With the partition key 2 items for 2.84 RU, both from the home list; Without the partition key 7 items for 2.34 RU, from the home, work and groceries lists; With a filter on listId 2 items for 2.84 RU, again only home

  • With the partition key: the two home items and nothing else.
  • Without the partition key: all seven items, from every list. When each partition belongs to one user or one tenant, this is everyone's data.
  • With a filter on listId: the same two items as the first query.

In this small container, the query without a partition key even cost slightly less: 2.34 request units against 2.84. That's expected. Microsoft's guidance: if you have only one (or just a few) physical partitions, cross-partition queries don't consume significantly more RUs than in-partition queries. A physical partition holds up to 50 GB, and the guidance is to avoid cross-partition queries when a container has over 30,000 RUs provisioned or stores over 100 GB of data, because then a query without a partition key must fan out to all physical partitions. In a small container, the difference that matters is which items come back.

The Complete File​

Program.cs
using System.Text.Json;
using Azure.Identity;
using Microsoft.Azure.Cosmos;

// The account's URI, from its Overview page in the Azure portal.
const string AccountEndpoint = "https://cosmos-maf-servicedesk-4224.documents.azure.com:443/";

using CosmosClient client = new(AccountEndpoint, new AzureCliCredential(), new CosmosClientOptions
{
UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Web,
});
Container todos = client.GetContainer("servicedesk", "howto-todos");

// Three to-do lists. Each list is one partition, because the container's partition key path is /listId.
// Upsert, so running the app again doesn't add the items twice.
TodoItem[] items =
[
new("1", "home", "Water the plants"),
new("2", "home", "Pay the electricity bill"),
new("3", "work", "Send the weekly report"),
new("4", "work", "Book a meeting room"),
new("5", "groceries", "Milk"),
new("6", "groceries", "Bread"),
new("7", "groceries", "Coffee"),
];
foreach (TodoItem item in items)
{
await todos.UpsertItemAsync(item, new PartitionKey(item.ListId));
}

QueryDefinition everything = new("SELECT * FROM c");

// 1. In the home list's partition only: the partition key is set in the request options.
await RunQueryAsync("With the partition key", everything, new QueryRequestOptions { PartitionKey = new PartitionKey("home") });

// 2. The same query without a partition key: every partition.
await RunQueryAsync("Without the partition key", everything, new QueryRequestOptions());

// 3. A filter on the partition key's property: Cosmos DB routes the query to that partition by itself.
QueryDefinition homeOnly = new QueryDefinition("SELECT * FROM c WHERE c.listId = @listId")
.WithParameter("@listId", "home");
await RunQueryAsync("With a filter on listId", homeOnly, new QueryRequestOptions());

async Task RunQueryAsync(string label, QueryDefinition query, QueryRequestOptions options)
{
using FeedIterator<TodoItem> feed = todos.GetItemQueryIterator<TodoItem>(query, requestOptions: options);

List<TodoItem> found = [];
double charge = 0;
while (feed.HasMoreResults)
{
FeedResponse<TodoItem> page = await feed.ReadNextAsync();
charge += page.RequestCharge;
found.AddRange(page);
}

Console.WriteLine($"{label}: {found.Count} items, {charge} RU");
foreach (TodoItem item in found)
{
Console.WriteLine($" {item.ListId}: {item.Title}");
}
}

record TodoItem(string Id, string ListId, string Title);

macOS-style code window titled Program.cs — TodoQuery showing the query SELECT * FROM c run once with QueryRequestOptions.PartitionKey set to home, once with empty QueryRequestOptions, and a third query with WHERE c.listId = @listId and WithParameter, plus RunQueryAsync, which reads every page with ReadNextAsync, adds up RequestCharge and prints each item's list and title

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out the partition key when each partition belongs to one userThe query returns every user's itemsSet QueryRequestOptions.PartitionKey, or filter on the partition key's property
Building the filter with string concatenationA value with a quote breaks the query, or changes itUse @parameters and WithParameter
Reading only the first pageLarger results are cut shortLoop while HasMoreResults
Filtering on the property with > or another rangeThe query isn't routed to one partitionFilter with =, or IN for a few partitions

Troubleshooting​

SymptomLikely causeFix
The query returns items from other partitionsNo partition key in the options and no filter on its propertyStep 3 or Step 5
The query returns nothingA different partition key value, or the property name in the filter doesn't match the item's JSON (case matters)Check the item in Data Explorer
Forbidden (403); Substatus: 5301Your account has no data role on the containerGive it a Cosmos DB data role

FAQ​

Which is better, the options or the filter?​

Both read one partition. The options keep the query text free of the partition key, which suits a query that's already written, such as SELECT * FROM c. The filter puts everything in the query, which suits queries you build or log.

Is a cross-partition query wrong?​

No. Microsoft says having some cross-partition queries is inevitable, which is okay. It matters when the results must belong to one partition, as with one user's data, and for cost in large containers.

Conclusion​

To read one logical partition of a Cosmos DB container from C#, set QueryRequestOptions.PartitionKey or filter on the partition key's property with =. Without either, a query reads every partition. In a small container that costs about the same, but it returns everyone's items.

Additional Resources​