Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 10 of 28
❮Prev Next❯

Cosmos DB for NoSQL: Connect with the SDK and Query

Module 2: Data for AI ⏱ 11 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    30-second answer

    You connect with the azure-cosmos Python SDK by creating a CosmosClient from the account endpoint and DefaultAzureCredential, then getting a database and a container. Write items with upsert_item, fetch one item cheaply with a point read (read_item with its id and partition key, about 1 RU for a 1 KB item), and use query_items with parameters for everything else. Pass partition_key to keep a query inside one logical partition; a query without it fans out across partitions and costs more Request Units.

    Simulate it » No Azure account needed

    Exam objective: 2.1.1 Connect to Azure Cosmos DB for NoSQL by using the SDK and run queries. (Skills measured as of October 7, 2026)

    Simulations

    Feel it before you read it. No account needed, nothing leaves this page.

    Azure portal: Create a Cosmos DB account, database and container Create an account, a database and a container with a partition key.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    Open <strong>Azure Cosmos DB</strong> and select <strong>+ Create</strong>.

    👆 Click the glowing item in the portal to continue

    Read the steps as text
    1. Open Azure Cosmos DB and select + Create.
    2. Pick the API first; you can’t change it later. New apps use Azure Cosmos DB for NoSQL.
    3. Choose Capacity mode. Provisioned throughput reserves RU/s; Serverless bills only the RUs you use, good for spiky dev traffic.
    4. Review and Create. The account takes a few minutes.
    5. Done. Go to resource.
    6. Open Data Explorer and select New Container.
    7. The partition key decides how data spreads. /categoryId has many values and matches your most common filter.
    8. The tree shows retail → products. Items with the same categoryId live together, so a query for one category reads one partition.

    🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.

    😟 THE PROBLEM

    Every chat history lookup scans the whole database.

    😊 THE SOLUTION

    Pick a good partition key and use point reads where you can.

    • Cross-partition queries✓ Filter on the partition key
    • Keys in config✓ DefaultAzureCredential
    • Big result sets✓ Paging with continuation tokens
    🛠️ Solved with: Cosmos DB SDK

    Start with a question

    Your AI shopping assistant needs a product's price and stock in under 10 milliseconds, thousands of times a minute. Where does that data live, and how does your code ask for it?

    Think of a huge warehouse with labelled aisles. If you know the aisle and the shelf number, a picker walks straight there and grabs the box. If all you’ve got is “something blue, about this big”, they have to walk every aisle.

    Azure Cosmos DB for NoSQL works the same way. The partition key is the aisle and the id is the shelf. Give both and you get a cheap, fast point read. Give a vague query and it walks the whole warehouse, and you pay for every step in Request Units.

    Explain it like I’m 10

    The technical explanation

    The hierarchy is simple: an account holds databases, a database holds containers, and a container holds JSON items. Each container has a partition key path, for example /category. Items with the same category value share a logical partition (up to 20 GB), and Cosmos DB spreads logical partitions across physical ones as you grow. An item’s id must be unique within its logical partition, and an item can be up to 2 MB.

    Connect with Microsoft Entra ID

    pip install azure-cosmos azure-identity
    export COSMOS_ENDPOINT="https://<account-name>.documents.azure.com:443/"
    az login
    import os
    from azure.cosmos import CosmosClient, PartitionKey
    from azure.identity import DefaultAzureCredential
    
    client = CosmosClient(
        url=os.environ["COSMOS_ENDPOINT"],
        credential=DefaultAzureCredential(),  # no account key in code
    )
    
    # Usually created by Bicep, the CLI or the portal (see the note below)
    database = client.create_database_if_not_exists(id="shop")
    container = database.create_container_if_not_exists(
        id="products",
        partition_key=PartitionKey(path="/category"),
    )

    Create the CosmosClient once and reuse it for the life of the app. It holds connections and caches routing information, so making a new client per request is slow and wastes resources.

    Write, read and query

    # Insert, or replace if this id + partition key already exists
    container.upsert_item({
        "id": "p-1001",
        "category": "kettles",
        "name": "Steel Kettle 1.7 L",
        "price": 2499,
        "stock": 42,
    })
    
    # Point read: id + partition key value. About 1 RU for a 1 KB item.
    item = container.read_item(item="p-1001", partition_key="kettles")
    print(item["name"])
    
    charge = container.client_connection.last_response_headers["x-ms-request-charge"]
    print("RU charge:", charge)
    
    # Parameterised query inside ONE logical partition
    cheap = container.query_items(
        query="SELECT c.id, c.name, c.price FROM c WHERE c.category = @cat AND c.price < @max",
        parameters=[
            {"name": "@cat", "value": "kettles"},
            {"name": "@max", "value": 3000},
        ],
        partition_key="kettles",
    )
    for row in cheap:
        print(row)
    
    # A query that must look across partitions
    low_stock = container.query_items(
        query="SELECT TOP 20 c.id, c.category, c.stock FROM c WHERE c.stock < @n",
        parameters=[{"name": "@n", "value": 5}],
        enable_cross_partition_query=True,
    )

    A few things to notice:

    • upsert_item inserts or replaces. Use create_item if you want an error when the id already exists, and replace_item or patch_item for updates.
    • read_item isn’t a query, it’s a direct lookup, and it’s always cheaper than SELECT * FROM c WHERE c.id = @id.
    • query_items returns a lazy iterator. Results come back in pages as you loop, and each page has its own RU charge. For paging in an API, use max_item_count and by_page() and hand the continuation token back to the caller.

    The query language in one table

    You wantWrite
    Pick fieldsSELECT c.id, c.name FROM c
    FilterWHERE c.category = @cat AND c.price < @max
    Limit resultsSELECT TOP 10 ... or OFFSET 0 LIMIT 10
    SortORDER BY c.price DESC (multi-property sorts need a composite index)
    Search inside an arrayWHERE ARRAY_CONTAINS(c.tags, @tag)
    Flatten an array in the itemSELECT t FROM c JOIN t IN c.tags
    CountSELECT VALUE COUNT(1) FROM c WHERE c.category = @cat

    JOIN in Cosmos DB works inside one item (across its arrays), never between items or containers. Model your data so a request needs one item or one partition.

    1. 1 Partition key in the filter?

      Yes: the SDK routes the query to one partition.

    2. 2 No partition key

      The query fans out to every physical partition.

    3. 3 Index lookup

      Filters use the indexing policy, so no full scan of items.

    4. 4 Results and charge

      Each page returns items plus x-ms-request-charge.

    What happens to a query
    Architect level Entra ID data access, and why create_* can fail

    Cosmos DB has two kinds of access. Control plane (Azure Resource Manager) is for creating accounts, databases and containers, and uses normal Azure roles. Data plane is for reading and writing items, and with Entra ID it uses Cosmos DB’s own role definitions, assigned with az cosmosdb sql role assignment create. The built-in ones are Cosmos DB Built-in Data Reader and Cosmos DB Built-in Data Contributor.

    Data plane roles don’t include management operations, so create_database_if_not_exists and create_container_if_not_exists can fail when you sign in with Entra ID. In production, create the database and container with Bicep, the CLI or the portal, then use client.get_database_client("shop") and database.get_container_client("products") in the app. Many teams also set disableLocalAuth on the account so account keys stop working altogether.

    Real-world business scenario

    Online grocery

    Fabrikam Grocers (fictional)

    The problem
    The chat assistant looked up product details with SELECT * FROM c WHERE c.id = @id across a 40 GB container. Each lookup cost many RUs, and at lunchtime peaks requests were throttled with 429 errors.
    What they used
    The team switched lookups to read_item with the product id and its /category partition key, kept one CosmosClient for the whole app, signed in with a managed identity and the Cosmos DB Built-in Data Contributor role, and moved the remaining searches to parameterised single-partition queries.
    Why that choice
    Point reads go straight to one partition and cost about 1 RU for small items, and Entra ID removed the account key from the app settings.
    The result
    The same provisioned throughput now handles peak traffic without throttling, and every query logs its x-ms-request-charge so expensive ones are spotted early.

    When to use it and when not to

    ✓ Use it when…

    • You need single-digit millisecond reads and writes of JSON data at any scale.
    • Most requests can name one item or one partition key value.
    • Your AI app wants app data and vectors in the same items.

    ✕ Think twice when…

    • You need joins across many tables and ad hoc reporting. A relational database like PostgreSQL fits better.
    • You can't find a partition key that most queries filter on. Every request would fan out.
    • You need a cache in front of a database for repeated reads. That's Azure Managed Redis.

    ↔ Alternatives to consider

    • Azure Database for PostgreSQL for relational data, SQL joins and pgvector.
    • Azure Managed Redis for in-memory caching and very fast key lookups.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    Test yourself with exercises

    5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.

    Question 1

    Question 1 of 5

    A container named products uses /category as its partition key. The application knows both the id and the category of the product that it needs.

    Which Python SDK call retrieves the product with the lowest Request Unit (RU) charge?

    Question 2

    Question 2 of 5

    A Python application connects to Azure Cosmos DB for NoSQL by using CosmosClient and DefaultAzureCredential. The developer has the Owner role on the Cosmos DB account, but every request to read items returns 403 Forbidden. What should you do?

    Question 3

    Question 3 of 5

    A web API passes a category value entered by a user to a Cosmos DB query. You must prevent query injection. What should you do?

    Question 4

    Question 4 of 5 · Select 2

    You are investigating the cost of operations in a Python application that uses the azure-cosmos SDK. Which TWO statements are true?

    Question 5

    Question 5 of 5

    You are designing a container for chat sessions. Most requests read or write the messages of one session, and there will be millions of sessions. Which partition key should you choose?

    Interview preparation

    Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.

    Beginner What's the cheapest way to read one item from Cosmos DB?

    Model answer

    A point read. I call read_item with the item's id and its partition key value. For a 1 KB item that's about 1 RU, which is cheaper and faster than running a SELECT that returns the same item.

    Interviewer follows up

    Why does it need the partition key as well as the id?

    You

    The id is only unique inside a logical partition, and the partition key tells Cosmos DB exactly which partition to go to. Without it, the service would have to look everywhere.

    Intermediate Why should queries use parameters instead of building the SQL string yourself?

    Model answer

    Parameters stop injection, because user input is never treated as query text. They also keep the query text the same each time, which makes it easier to read and to reuse. In Python I pass a list like [{"name": "@cat", "value": category}].

    Experienced developer How do you find out how many RUs an operation cost from the Python SDK?

    Model answer

    Every response carries an x-ms-request-charge header. After the call I read container.client_connection.last_response_headers["x-ms-request-charge"]. I log it during development so an expensive query shows up before it reaches production.

    Scenario Your app connects with DefaultAzureCredential but every data call fails with 403 Forbidden, even though you're an Owner on the account. Why?

    Model answer

    Cosmos DB data access with Microsoft Entra ID uses its own data plane role assignments, not Azure IAM roles like Owner. I'd assign the Cosmos DB Built-in Data Contributor role (or Reader) to my identity on the account with az cosmosdb sql role assignment create.

    Architecture & design How do you pick a partition key for a product catalogue that an AI assistant queries?

    Model answer

    I look at the queries first. If most lookups filter by category, /category spreads writes well and keeps those queries in one partition. It needs plenty of distinct values and no single value that grows past the 20 GB logical partition limit. If one tenant or category could get huge, I'd look at a hierarchical partition key such as tenantId then category.

    Quick revision

    Key points

    • CosmosClient(url, credential=DefaultAzureCredential()) signs in with Microsoft Entra ID.
    • Entra ID data access needs a Cosmos DB data plane role such as Cosmos DB Built-in Data Contributor.
    • A container's partition key is set at creation and can't be changed.
    • upsert_item inserts or replaces; read_item is a point read by id and partition key.
    • query_items takes parameters; partition_key keeps it in one partition.
    • The RU charge is in the x-ms-request-charge response header.

    Important terminology

    Azure Cosmos DB for NoSQL
    A globally distributed database that stores schema-free JSON items and is queried with a SQL-like language.
    Container
    The unit that holds items, has a partition key, an indexing policy and throughput.
    Partition key
    An item property (such as /category) whose value decides which logical partition an item lives in. It can't be changed after the container is created.
    Point read
    Reading a single item by its id and partition key value, the cheapest operation in Cosmos DB.
    Request Unit (RU)
    The currency for Cosmos DB throughput; every read, write and query is charged in RUs.
    Upsert
    Insert the item if it doesn't exist, or replace it if an item with the same id and partition key does.
    Cross-partition query
    A query that can't be routed to one logical partition and so runs against every physical partition.

    Common mistakes

    • Running SELECT * FROM c WHERE c.id = @id instead of a point read.
    • Concatenating user input into query text instead of using parameters.
    • Expecting the Owner or Contributor Azure role to grant data access through Entra ID.

    Exam tips

    • "Retrieve one item with the lowest RU cost" = read_item with id and partition key.
    • "Query must not scan every partition" = filter on the partition key or pass partition_key.
    • "Check the RU cost of an operation" = the x-ms-request-charge header.

    Five quick revision questions

    1. 1.Which Python package is the Cosmos DB SDK?Show

      azure-cosmos.

    2. 2.Which method inserts an item or replaces it if it already exists?Show

      upsert_item.

    3. 3.What two values does a point read need?Show

      The item id and its partition key value.

    4. 4.Roughly how many RUs does a point read of a 1 KB item cost?Show

      About 1 RU.

    5. 5.Which header holds the RU charge?Show

      x-ms-request-charge.

    Official references

    Finished this lesson? Tick it off. Your progress is saved in this browser.

    Next up: Cosmos DB: RUs, Indexing Policies and Consistency Levels

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.