Azure Cosmos DB SDK Overview

This document provides comprehensive guidance on using the Azure Cosmos DB SDKs to interact with your NoSQL data. Azure Cosmos DB is a globally distributed, multi-model database service that enables you to harness the benefits of geo-distribution. The SDKs simplify the process of creating, reading, updating, and deleting (CRUD) data, as well as executing complex queries.

We support multiple programming languages, allowing you to integrate Cosmos DB seamlessly into your applications. Choose the SDK that best fits your development stack:

  • .NET
  • Java
  • Node.js
  • Python
  • JavaScript
  • Go
  • Spring Data Azure Cosmos DB

Installation

The installation process varies depending on the SDK you choose. Typically, you will use a package manager relevant to your language.

Select your language:

dotnet add package Microsoft.Azure.Cosmos

Getting Started with the SDK

Here's a basic example demonstrating how to connect to your Cosmos DB account and perform a simple operation.

Example: .NET SDK

using Microsoft.Azure.Cosmos; using System; using System.Threading.Tasks; public class Program { private static readonly string Endpoint = "YOUR_COSMOS_DB_ENDPOINT"; private static readonly string Key = "YOUR_COSMOS_DB_KEY"; private static readonly string DatabaseId = "your-database-id"; private static readonly string ContainerId = "your-container-id"; public static async Task Main(string[] args) { using (CosmosClient client = new CosmosClient(Endpoint, Key)) { Database database = await client.CreateDatabaseIfNotExistsAsync(DatabaseId); Container container = await database.CreateContainerIfNotExistsAsync(ContainerId, "/partitionKey"); var item = new { id = "item1", category = "widget", name = "My Widget", quantity = 5, description = "A sample widget" }; ItemResponse createdResponse = await container.CreateItemAsync(item, new PartitionKey(item.category)); Console.WriteLine($"Created item: {createdResponse.Resource.id}"); Console.WriteLine($"Request charge: {createdResponse.RequestCharge}"); } } }

Remember to replace YOUR_COSMOS_DB_ENDPOINT and YOUR_COSMOS_DB_KEY with your actual credentials. Ensure your container has a partition key defined.

Core Concepts

Understanding these fundamental concepts will help you effectively use the Cosmos DB SDKs:

  • Account: Your Cosmos DB instance, which can contain multiple databases.
  • Database: A logical namespace that groups containers.
  • Container: The core storage unit for your data. It holds items and has a schema-agnostic data model.
  • Item: A JSON document stored within a container.
  • Partition Key: A property within your JSON documents that dictates how data is distributed across physical partitions, crucial for scalability and performance.
  • Request Units (RUs): The measure of throughput in Cosmos DB. Each operation consumes RUs.

SDK Reference - Common Operations

The SDKs provide a rich set of APIs for managing your data.

Data Operations

Performing CRUD operations on items.

Create Item

Add a new JSON document to a container.

// Example C# syntax await container.CreateItemAsync<T>(item, new PartitionKey(partitionKeyValue));

Read Item

Retrieve a specific item by its ID and partition key.

// Example C# syntax ItemResponse<T> response = await container.ReadItemAsync<T>(itemId, new PartitionKey(partitionKeyValue));

Update Item

Replace an existing item.

// Example C# syntax ItemResponse<T> response = await container.ReplaceItemAsync<T>(updatedItem, itemId, new PartitionKey(partitionKeyValue));

Delete Item

Remove an item from the container.

// Example C# syntax await container.DeleteItemAsync<T>(itemId, new PartitionKey(partitionKeyValue));

Querying Data

Cosmos DB uses a SQL-like query language. The SDKs provide methods to execute these queries.

// Example C# syntax var queryDefinition = new QueryDefinition("SELECT * FROM c WHERE c.category = @category") .WithParameter("@category", "widget"); var resultSet = container.GetItemQueryIterator<dynamic>(queryDefinition); while (resultSet.HasMoreResults) { var response = await resultSet.ReadNextAsync(); foreach (var item in response) { Console.WriteLine($"Item: {item.name}"); } }

Indexing

Cosmos DB automatically indexes all data written to the database. The SDKs allow you to customize indexing policies, including included/excluded paths and index kinds (e.g., range, spatial, composite).

Default Indexing: All properties are indexed by default.

Customization: Via IndexingPolicy settings when creating or updating containers.

Partitioning Strategy

Choosing an effective partition key is critical for performance and scalability. A good partition key distributes requests evenly across logical partitions.

  • Cardinality: Aim for high cardinality (many unique values) in your partition key.
  • Hot Partitions: Avoid partition keys that concentrate traffic on a few partitions.
  • Common Choices: User ID, Tenant ID, Timestamp (with careful design).

The SDKs require you to provide the partition key value when performing most operations on an item.

Best Practices

  • Reuse CosmosClient: Instantiate CosmosClient once and reuse it throughout your application's lifetime.
  • Efficient Queries: Write queries that leverage partition keys and filters effectively. Avoid cross-partition queries where possible.
  • Handle Throttling: Implement retry logic for requests that return 429 (Too Many Requests) status codes. The SDKs often have built-in retry policies.
  • Optimal Consistency Level: Choose the lowest consistency level that meets your application's requirements to minimize latency.
  • Monitor Throughput: Keep an eye on Request Units (RUs) consumption and scale your throughput as needed.

Troubleshooting Common Issues

  • 429: Too Many Requests: Indicates you've exceeded your provisioned throughput. Scale up your RU/s or implement retry logic.
  • 1004: Resource Not Found: Ensure the database, container, or item ID is correct and that the resource exists.
  • Partition Key Mismatch: Double-check that the partition key value provided during operations matches the item's actual partition key.

API Reference Summary

Operation Method Description
Create Item POST Adds a new item to a container.
Read Item GET Retrieves an item by ID and partition key.
Update Item PUT Replaces an existing item.
Delete Item DELETE Removes an item.
Query Items POST (Query endpoint) Executes a SQL-like query against the container.