Azure Cosmos DB .NET SDK
This tutorial guides you through the essential steps of using the Azure Cosmos DB .NET SDK to interact with your NoSQL data. We'll cover creating resources, performing CRUD operations, and querying data.
Prerequisites
- An Azure subscription. Create one for free.
- An Azure Cosmos DB account. Create a Cosmos DB account.
- Visual Studio 2019 or later, or .NET SDK installed.
- Basic understanding of C# and asynchronous programming.
1. Install the NuGet Package
First, you need to add the Azure Cosmos DB .NET SDK to your project. Open your project in Visual Studio or use the .NET CLI and run the following command:
dotnet add package Microsoft.Azure.Cosmos
2. Initialize the Cosmos DB Client
To connect to your Cosmos DB account, you need to initialize the CosmosClient. You'll need your account's endpoint and primary key, which can be found in the Azure portal.
using Microsoft.Azure.Cosmos;
// Your Cosmos DB endpoint and key
string endpoint = "YOUR_COSMOS_DB_ENDPOINT";
string key = "YOUR_COSMOS_DB_PRIMARY_KEY";
// Initialize the Cosmos client
CosmosClient client = new CosmosClient(endpoint, key);
3. Create a Database and Container
Next, you'll create a database and a container within that database. A container is where your data is stored.
// Reference to the database
Database database = await client.CreateDatabaseIfNotExistsAsync("ToDoList");
// Reference to the container
Container container = await database.CreateContainerIfNotExistsAsync("Items", "/category");
// The "/category" is the partition key path. Choose a property that distributes your data evenly.
4. Create an Item (Document)
Now, let's add some data to your container. Items in Cosmos DB are typically JSON documents.
First, define a C# class to represent your item:
public class TodoItem
{
public string id { get; set; }
public string description { get; set; }
public string category { get; set; }
public bool isComplete { get; set; }
}
Then, create and add the item:
TodoItem newItem = new TodoItem
{
id = Guid.NewGuid().ToString(), // Unique identifier for the item
description = "Buy groceries",
category = "Personal",
isComplete = false
};
ItemResponse response = await container.CreateItemAsync(newItem, new PartitionKey(newItem.category));
Console.WriteLine($"Created item with id: {response.Resource.id}");
5. Read an Item
You can retrieve a specific item using its ID and partition key.
string itemId = "YOUR_ITEM_ID"; // Replace with the actual ID of the item you want to read
string itemCategory = "Personal"; // Replace with the actual category
ItemResponse readResponse = await container.ReadItemAsync(itemId, new PartitionKey(itemCategory));
TodoItem retrievedItem = readResponse.Resource;
Console.WriteLine($"Retrieved item: {retrievedItem.description}");
6. Update an Item
To update an item, you can use the UpsertItemAsync method. If the item exists, it will be updated; otherwise, it will be created.
// Assume 'retrievedItem' is the item fetched in the previous step
retrievedItem.isComplete = true;
ItemResponse updateResponse = await container.UpsertItemAsync(retrievedItem, new PartitionKey(retrievedItem.category));
Console.WriteLine($"Updated item with id: {updateResponse.Resource.id}. Is Complete: {updateResponse.Resource.isComplete}");
7. Delete an Item
Delete an item using its ID and partition key.
string itemIdToDelete = "YOUR_ITEM_ID"; // Replace with the ID of the item to delete
string itemCategoryToDelete = "Personal"; // Replace with the category
await container.DeleteItemAsync(itemIdToDelete, new PartitionKey(itemCategoryToDelete));
Console.WriteLine($"Deleted item with id: {itemIdToDelete}");
8. Query Items
Cosmos DB supports rich querying using SQL. You can use the GetItemQueryIterator method.
string queryText = "SELECT * FROM c WHERE c.isComplete = false";
QueryDefinition queryDefinition = new QueryDefinition(queryText);
FeedIterator queryIterator = container.GetItemQueryIterator(queryDefinition);
while (queryIterator.HasMoreResults)
{
FeedResponse response = await queryIterator.ReadNextAsync();
foreach (TodoItem item in response)
{
Console.WriteLine($"Incomplete item: {item.description}");
}
}
Next Steps
- Learn about indexing policies for better query performance.
- Understand throughput provisioning for your containers.
- Explore change feed for real-time data processing.