Cosmos DB for NoSQL: Connect with the SDK and Query
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.
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.
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
- Open Azure Cosmos DB and select + Create.
- Pick the API first; you can’t change it later. New apps use Azure Cosmos DB for NoSQL.
- Choose Capacity mode. Provisioned throughput reserves RU/s; Serverless bills only the RUs you use, good for spiky dev traffic.
- Review and Create. The account takes a few minutes.
- Done. Go to resource.
- Open Data Explorer and select New Container.
- The partition key decides how data spreads. /categoryId has many values and matches your most common filter.
- 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.
🖱️ Drag to rotate · scroll or pinch to zoom
Cosmos DB: items, partitions, RUs
In Azure Cosmos DB for NoSQL, JSON items live in containers, spread across logical partitions by the partition key. Every operation costs Request Units (RUs). A point read by id and partition key costs about 1 RU. A query that scans every partition costs far more.
🤔 What happens if…
Read this tour as text
- Text becomes a vector. An embedding model turns text into a list of numbers, a vector (1,536 numbers for
text-embedding-3-small). Texts that mean similar things get vectors that sit close together, so "refund" lands near "money back". - Cosmos DB: items, partitions, RUs. In Azure Cosmos DB for NoSQL, JSON items live in containers, spread across logical partitions by the partition key. Every operation costs Request Units (RUs). A point read by id and partition key costs about 1 RU. A query that scans every partition costs far more.
- Indexing and consistency. By default Cosmos DB indexes every property, so writes cost more RUs. An indexing policy can exclude paths you never filter on, such as the big
embeddingarray. Consistency levels trade freshness for speed and cost: Strong, Bounded staleness, Session (default), Consistent prefix, Eventual. - Vector search in Cosmos DB. A vector embedding policy tells Cosmos DB where the vectors are, their dimensions and distance function. A vector index makes search fast:
diskANNorquantizedFlatfor large sets, orflatfor exact search on small vectors (up to 505 dimensions). ThenORDER BY VectorDistance(c.embedding, @q)returns the closest items. - Change feed. The change feed is an ordered log of inserts and updates in a container (deletes only show up in the *all versions and deletes* mode). A change feed processor reads it with a lease container that remembers how far each worker got, so a new product can be embedded the moment it’s saved.
- PostgreSQL with pgvector. In Azure Database for PostgreSQL, the pgvector extension adds a
vector(1536)column type. Without an index, every search compares against every row (a sequential scan). An HNSW or IVFFlat index finds near neighbours fast, trading a little recall for a lot of speed. - RAG with a metadata filter. Retrieval-augmented generation (RAG): embed the question, fetch the closest chunks (
ORDER BY embedding <=> $1 LIMIT 5), filter by metadata such astenant_idorlang, then send those chunks to the model as context. The answer is grounded in your own data. - Azure Managed Redis. Azure Managed Redis keeps hot data in memory. Cache-aside: check Redis, and on a miss read the database and store the result with a TTL. When data changes, invalidate the key. Redis can also hold a vector index for fast similarity search, for example a semantic cache of answers.
Every Cosmos DB call has a price in request units. Create an orders container, read data three ways from Python and compare the bill, then change consistency and indexing and watch the numbers move.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 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
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_itemif you want an error when the id already exists, andreplace_itemorpatch_itemfor 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_countandby_page()and hand the continuation token back to the caller.
The query language in one table
| You want | Write |
|---|---|
| Pick fields | SELECT c.id, c.name FROM c |
| Filter | WHERE c.category = @cat AND c.price < @max |
| Limit results | SELECT TOP 10 ... or OFFSET 0 LIMIT 10 |
| Sort | ORDER BY c.price DESC (multi-property sorts need a composite index) |
| Search inside an array | WHERE ARRAY_CONTAINS(c.tags, @tag) |
| Flatten an array in the item | SELECT t FROM c JOIN t IN c.tags |
| Count | SELECT 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 Partition key in the filter?
Yes: the SDK routes the query to one partition.
-
2 No partition key
The query fans out to every physical partition.
-
3 Index lookup
Filters use the indexing policy, so no full scan of items.
-
4 Results and charge
Each page returns items plus x-ms-request-charge.
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
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.
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.
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.Which Python package is the Cosmos DB SDK?Show
azure-cosmos.
-
2.Which method inserts an item or replaces it if it already exists?Show
upsert_item.
-
3.What two values does a point read need?Show
The item id and its partition key value.
-
4.Roughly how many RUs does a point read of a 1 KB item cost?Show
About 1 RU.
-
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
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.