Getting Started with Azure Cosmos DB

Welcome to Azure Cosmos DB! This guide will walk you through the essential steps to begin using Azure Cosmos DB, a globally distributed, multi-model database service. Whether you're building a new application or migrating an existing one, Cosmos DB offers unparalleled flexibility and scalability.

Azure Cosmos DB Architecture
Azure Cosmos DB: A Globally Distributed, Multi-Model Database Service

What is Azure Cosmos DB?

Azure Cosmos DB is Microsoft's globally distributed, multi-model database service. It enables you to elastically and independently scale throughput and storage across any number of geographic regions. You can read and write data from regions faster, and take advantage of low latency global distribution, multi-master writes, and always-on availability.

Prerequisites

Before you begin, ensure you have the following:

Step 1: Create an Azure Cosmos DB Account

The first step is to create an Azure Cosmos DB account in the Azure portal.

  1. Sign in to the Azure portal.
  2. In the top left corner, select Create a resource.
  3. In the search box, type Azure Cosmos DB and then select it.
  4. Select Create.
  5. On the Create Azure Cosmos DB API page, choose the API you want to use (e.g., Core (SQL) API, MongoDB API, Cassandra API, Gremlin API, Table API). For this guide, we'll assume you're using the Core (SQL) API. Select Create under Core (SQL) API.
  6. Fill in the required details on the Create Azure Cosmos DB account page:
    • Subscription: Select your Azure subscription.
    • Resource group: Create a new one or select an existing one.
    • Account Name: Enter a unique name for your Cosmos DB account.
    • Location: Choose a region closest to your users.
    • Capacity mode: Select either "Autoscale" or "Manual" based on your needs.
  7. Review the settings and select Review + create, then Create.

Step 2: Create a Database and Container

Once your account is deployed, you'll need to create a database and containers (collections in MongoDB API, tables in Table API) to store your data.

Note: In the Core (SQL) API, a database is a logical namespace for containers. A container is the unit of scalability for throughput and storage.
  1. Navigate to your newly created Azure Cosmos DB account in the Azure portal.
  2. In the left-hand navigation menu, under Data Explorer, select New Container.
  3. In the New Container pane:
    • Database id: Enter a name for your database (e.g., ToDoList). You can also select an existing database.
    • Container id: Enter a name for your container (e.g., Items).
    • Partition key: Select a property from your documents to partition your data (e.g., /categoryId). A good partition key is crucial for performance and scalability.
    • Throughput: Choose between "Autoscale" or "Manual" throughput. For initial testing, manual throughput of 400 RU/s is often sufficient.
  4. Select OK.

Step 3: Add Data

You can add data to your container using the Data Explorer in the Azure portal or by using one of the Azure Cosmos DB SDKs.

Using Data Explorer:

  1. In Data Explorer, expand your database and select your container (e.g., Items).
  2. Select New Item.
  3. Enter your JSON document in the editor. For example:
    {
        "id": "84151b4b-3f7a-4741-a257-51c75285c922",
        "categoryId": "books",
        "name": "Azure Cosmos DB: The Definitive Guide",
        "description": "A comprehensive guide to Azure Cosmos DB features and capabilities.",
        "author": "Microsoft",
        "publishDate": "2023-10-27T10:00:00Z",
        "tags": [
            "cosmosdb",
            "azure",
            "nosql"
        ]
    }
  4. Select Save.

Using SDKs (Example with .NET):

To interact with Cosmos DB programmatically, you'll need to install the appropriate SDK for your language. Here's a brief example using the .NET SDK:

Prerequisites for SDK: Ensure you have the .NET SDK installed and the Azure Cosmos DB .NET SDK NuGet package added to your project.
// Get the connection string from your Cosmos DB account's "Keys" section in the Azure portal.
string cosmosDbConnectionString = "YOUR_COSMOS_DB_CONNECTION_STRING";
string databaseId = "ToDoList";
string containerId = "Items";

using (var client = new CosmosClient(cosmosDbConnectionString))
{
    // Get a reference to the database
    var database = client.GetDatabase(databaseId);

    // Get a reference to the container
    var container = database.GetContainer(containerId);

    // Define a new item
    var newItem = new {
        id = Guid.NewGuid().ToString(),
        categoryId = "guides",
        name = "Getting Started with Cosmos DB",
        description = "A quick start guide for new users.",
        author = "Your Name",
        publishDate = DateTime.UtcNow,
        tags = new List<string> { "cosmosdb", "azure", "quickstart" }
    };

    try
    {
        // Create the item
        ItemResponse<dynamic> response = await container.CreateItemAsync(newItem);
        Console.WriteLine($"Item created with ID: {response.Resource.id}");
    }
    catch (CosmosException ex)
    {
        Console.WriteLine($"Error creating item: {ex.StatusCode}");
    }
}

Step 4: Query Your Data

Once data is in your container, you can query it using SQL-like queries.

Using Data Explorer:

  1. In Data Explorer, select your container (e.g., Items).
  2. Select the New SQL Query button.
  3. Enter your query. For example, to get all items in the "books" category:
    SELECT * FROM c WHERE c.categoryId = 'books'
  4. Select Execute SQL Query.

Using SDKs (Example with .NET):

// ... (assuming client, database, and container are already initialized as above)

try
{
    var query = new QueryDefinition("SELECT * FROM c WHERE c.categoryId = @categoryId")
        .WithParameter("@categoryId", "guides");

    var results = container.GetItemQueryIterator<dynamic>(query);

    Console.WriteLine("Query Results:");
    while (results.HasMoreResults)
    {
        var response = await results.ReadNextAsync();
        foreach (var item in response)
        {
            Console.WriteLine($"- {item.name} ({item.id})");
        }
    }
}
catch (CosmosException ex)
{
    Console.WriteLine($"Error executing query: {ex.StatusCode}");
}

Next Steps

Congratulations! You've successfully set up Azure Cosmos DB, created a database and container, added data, and performed a query.

To learn more, explore these resources: