Perform operations on Cosmos DB containers and items using SDK
5 minutes
5 Questions
Azure Cosmos DB SDK enables developers to programmatically interact with containers and items through various operations. The SDK is available for multiple languages including .NET, Java, Python, and JavaScript.
To begin working with Cosmos DB, you first establish a connection using CosmosClient b…Azure Cosmos DB SDK enables developers to programmatically interact with containers and items through various operations. The SDK is available for multiple languages including .NET, Java, Python, and JavaScript.
To begin working with Cosmos DB, you first establish a connection using CosmosClient by providing the endpoint URI and primary key. From there, you can access databases and containers.
Container Operations:
- Create containers using CreateContainerIfNotExistsAsync() method, specifying container properties like partition key path and throughput settings
- Read container properties using ReadContainerAsync()
- Replace container settings with ReplaceContainerAsync()
- Delete containers using DeleteContainerAsync()
- Query containers using GetContainerQueryIterator()
Item Operations:
- Create items using CreateItemAsync<T>(), where T is your data model class. You must provide the item object and partition key value
- Read individual items with ReadItemAsync<T>() using the item ID and partition key
- Replace existing items using ReplaceItemAsync<T>()
- Upsert items (create or update) with UpsertItemAsync<T>()
- Delete items using DeleteItemAsync<T>()
Querying Items:
The SDK supports SQL-like queries through GetItemQueryIterator<T>(). You can create QueryDefinition objects with parameterized queries for security and performance. Results are returned as pages that you iterate through using FeedIterator.
Best Practices:
- Always specify partition keys for optimal performance
- Use async/await patterns for non-blocking operations
- Implement proper exception handling for CosmosException
- Configure appropriate RequestOptions for consistency levels and throughput
- Dispose CosmosClient properly or use singleton pattern
- Leverage bulk operations for high-volume scenarios using AllowBulkExecution option
The SDK also supports transactional batch operations within the same partition key, enabling atomic operations across multiple items. This ensures data consistency when performing related modifications together.
Perform Operations on Cosmos DB Containers and Items Using SDK
Why It Is Important
Azure Cosmos DB is a globally distributed, multi-model database service that is fundamental to modern cloud applications. Understanding how to perform operations on containers and items using the SDK is critical for the AZ-204 exam because it represents real-world development scenarios. Developers must know how to programmatically create, read, update, and delete data in Cosmos DB to build scalable, high-performance applications.
What It Is
The Cosmos DB SDK provides a programmatic interface for interacting with Azure Cosmos DB resources. Key concepts include:
Containers: Logical resources that store items, stored procedures, triggers, and user-defined functions. Containers are schema-agnostic and are the unit of scalability for throughput and storage.
Items: The individual documents or records stored within a container. In the SQL API, these are JSON documents.
Partition Key: A property that determines how data is distributed across physical partitions. Choosing the right partition key is essential for performance.
How It Works
The .NET SDK (Microsoft.Azure.Cosmos) is commonly tested. Here are the key operations:
1. Creating a CosmosClient: CosmosClient client = new CosmosClient(endpoint, key);
2. Creating a Database: Database database = await client.CreateDatabaseIfNotExistsAsync("myDatabase");
4. Creating an Item: ItemResponse<MyItem> response = await container.CreateItemAsync(item, new PartitionKey(item.PartitionKey));
5. Reading an Item: ItemResponse<MyItem> response = await container.ReadItemAsync<MyItem>(id, new PartitionKey(partitionKeyValue));
6. Replacing an Item: ItemResponse<MyItem> response = await container.ReplaceItemAsync(updatedItem, id, new PartitionKey(partitionKeyValue));
7. Upserting an Item: ItemResponse<MyItem> response = await container.UpsertItemAsync(item, new PartitionKey(item.PartitionKey));
8. Deleting an Item: ItemResponse<MyItem> response = await container.DeleteItemAsync<MyItem>(id, new PartitionKey(partitionKeyValue));
9. Querying Items: QueryDefinition query = new QueryDefinition("SELECT * FROM c WHERE c.category = @category").WithParameter("@category", "electronics"); FeedIterator<MyItem> iterator = container.GetItemQueryIterator<MyItem>(query);
Exam Tips: Answering Questions on Perform Operations on Cosmos DB Containers and Items Using SDK
• Know the difference between CreateItemAsync and UpsertItemAsync: CreateItemAsync fails if the item exists, while UpsertItemAsync creates or updates.
• Partition Key is mandatory: Most operations require you to specify the partition key value. Remember that ReadItemAsync and DeleteItemAsync need both the item ID and partition key.
• Understand throughput provisioning: Know that throughput (RU/s) can be set at database or container level. Container-level is more granular.
• FeedIterator pattern: Queries return results in pages. Use FeedIterator to iterate through all results with HasMoreResults and ReadNextAsync.
• Point reads vs queries: Point reads (ReadItemAsync with ID and partition key) are more efficient than queries. Expect questions comparing these approaches.
• Consistency levels: Understand the five consistency levels (Strong, Bounded Staleness, Session, Consistent Prefix, Eventual) and when to use each.
• Exception handling: Be familiar with CosmosException and checking StatusCode for handling 404 (not found) or 429 (rate limiting) scenarios.
• Connection modes: Know that Gateway mode uses HTTPS while Direct mode uses TCP for better performance.