Home › Studies › AI-200 › AI Data Services › Cosmos DB for NoSQL & Vectors

Cosmos DB for NoSQL & Vectors

Python SDK · queries · indexing policy · RUs · consistency levels · vector search · change feed

By the tools4free.dev team · Last reviewed November 13, 2026

Practice questions for this topic →

Connect with the Python SDK

The client library is the azure-cosmos package. Install azure-identity as well to authenticate with DefaultAzureCredential.

TaskCallNotes
Installpip install azure-cosmos and pip install azure-identityBoth packages are listed in requirements.txt in the quickstart.
Authenticatecredential = DefaultAzureCredential() then client = CosmosClient(url="<azure-cosmos-db-nosql-account-endpoint>", credential=credential)CosmosClient is the primary client class: account-wide metadata and databases.
Get a databaseclient.get_database_client("cosmicworks")Returns a DatabaseProxy.
Get a containerdatabase.get_container_client("products")Returns a ContainerProxy: read, update and delete on the container or its items.
Create or replace an itemcontainer.upsert_item(new_item)Upserts: replaces the item if it already exists.
Point readcontainer.read_item(item="<id>", partition_key="<key>")Needs both the id and the partition key.
Querycontainer.query_items(query=..., parameters=[...], enable_cross_partition_query=False)Parameterized: SELECT * FROM products p WHERE p.category = @category.

Indexing policy and RU cost

SettingRule
Default policyIndexes every property of every item and enforces range indexes for any string or number.
Mode ConsistentIndex updated synchronously as items are created, updated or deleted; read queries use the account's consistency.
Mode NoneIndexing disabled. Used for a pure key-value store, or to speed up bulk operations; then set Consistent again and watch IndexTransformationProgress.
Lazy modeCan give inconsistent or incomplete query results. New containers can't select it.
Property pathsScalar path ends with /?; array elements use /[]; /* matches everything below a node.
Root pathEvery policy must include /* as an included or an excluded path. Including it and excluding what you don't need is the recommended approach.
PrecedenceIf included and excluded paths conflict, the more precise path wins.
System propertiesid and _ts are indexed in Consistent mode; _etag is excluded by default.

Composite indexes

What drives RU charges

Consistency levels

From strongest to weakest: Strong, Bounded staleness, Session, Consistent prefix, Eventual. The account default applies to all databases and containers; a single request or SDK client can override it for reads.

LevelGuaranteeReads
StrongLinearizability: reads return the most recent committed version.Two replicas (local minority); about 2x RU cost
Bounded stalenessLag is less than K versions or T time, whichever is reached first. Primarily beneficial to single-write-region accounts with two or more regions.Two replicas; about 2x RU cost
SessionWithin one client session: read-your-writes and write-follows-reads. Uses a session token. Most widely used level.Single replica
Consistent prefixReads never see out-of-order writes; a transaction's writes are visible together.Single replica
EventualWeakest: a read can return older values than ones read before. No ordering guarantee.Single replica

Vector search

Vectors are stored in the documents next to the data. Enable the feature on the account first (portal Features, or --capabilities EnableNoSQLVectorSearch; it can take 15 minutes). Vector search works on new containers only: set the vector embedding policy and the vector index when you create the container.

Vector policy fieldValue
pathProperty that holds the vector (required). One policy per path.
dataTypefloat32, float16, int8 or uint8. float16 can cut vector storage by 50% with some accuracy loss.
dimensionsLength of each vector. Default 1536.
distanceFunctioncosine (default, -1 to +1, higher is more similar), dotproduct, euclidean (0 is most similar).
Vector indexBehaviorMax dimensions
flatBrute force, 100% recall.505
quantizedFlatBrute force over compressed vectors; slightly lower accuracy. Recommended when 50,000 or fewer vectors are in scope.4096
diskANNApproximate nearest neighbor; can offer some of the lowest latency and RU cost. In general the most performant index type when the search scope is over 50,000 vectors.4096
Python callPurpose
create_container_if_not_exists(id=..., partition_key=PartitionKey(path='/id'), indexing_policy=indexing_policy, vector_embedding_policy=vector_embedding_policy)Create the container with both policies.
query_items(query='SELECT c.title, VectorDistance(c.contentVector,@embedding) AS SimilarityScore FROM c ORDER BY VectorDistance(c.contentVector,@embedding)', parameters=[{"name": "@embedding", "value": query_embedding}], enable_cross_partition_query=True)Vector search with the embedding as a parameter.

Change feed and the change feed processor

Change feed processorPull model
SDKs.NET V3 and Java onlyPython and Node.js (the processor library is only for .NET and Java)
Progress trackingLease documents in a lease containerContinuation token (in memory or saved by you)
DeliveryAutomatic checkpointing, at-least-onceYou manage checkpoints
PollingAutomatic, WithPollIntervalManual
One partition key onlyNot supportedYes
ParallelismAutomatic across instancesManual, with FeedRange

Processor components and life cycle

Python pull-model callPurpose
container.query_items_change_feed(start_time="Beginning")Read the whole container's feed from the start.
container.query_items_change_feed(start_time="Beginning", partition_key=pk)Only one partition key's changes.
container.read_feed_ranges(force_refresh=False)One feed_range per physical partition, to parallelize.
container.query_items_change_feed(continuation=continuation_token)Resume from a saved continuation token.
container.query_items_change_feed(mode="AllVersionsAndDeletes")All versions and deletes mode (Python SDK 4.9.1b1 or later). Default mode is LatestVersion.

CLI and PowerShell

TaskAzure CLIPowerShell
Enable NoSQL vector search on an accountaz cosmosdb update --resource-group <resource-group-name> --name <account-name> --capabilities EnableNoSQLVectorSearch-

Exam Tips

Tick each tip once you can answer it without looking.

“Fetch one known item by ID and partition key in Python” → container.read_item(item=..., partition_key=...) (point read). Trap: query_items works but a point read costs fewer RUs than a query; upsert_item writes.

“Create the item, or replace it if it exists” → container.upsert_item. Trap: read_item only reads; get_container_client only returns a client object.

“Python packages for a Cosmos DB app using Entra ID” → azure-cosmos and azure-identity (CosmosClient + DefaultAzureCredential). Trap: redis-entraid belongs to the Redis quickstart.

“Multi-property ORDER BY fails or costs too much” → Add a composite index with the same path sequence and order (or the exact opposite on all paths). Trap: Reversed path order, or mixed ASC/DESC that doesn't match, isn't supported by the index.

“Filter on one equality and one range property” → Composite index with the equality property first and the range property last. Trap: One composite index can optimize only one range filter; two range filters need two indexes.

“Cut write RUs for items with many properties you never filter on” → Keep root /* included and exclude the unneeded paths. Trap: Don't drop the root path (policy must include /* as included or excluded), and Lazy mode isn't available on new containers.

“One-time bulk load, queries needed afterwards” → Indexing mode None during the load, then Consistent; track IndexTransformationProgress. Trap: Mode None disables indexing on the container, so it can't stay on None if you query afterwards.

“Per-user read-your-writes, best-known default” → Session consistency. Trap: Strong and bounded staleness double read RU cost; Eventual gives no ordering.

“Which levels read from two replicas (about 2x read RU)” → Strong and Bounded staleness. Trap: Session, Consistent prefix and Eventual use single-replica reads.

“Changed the account default consistency level” → Restart the app so the SDK instance is recreated. Trap: A running SDK instance keeps using the old default.

“Vector search over more than 50,000 vectors in scope, up to 4096 dimensions” → diskANN. Trap: flat stops at 505 dimensions; quantizedFlat is recommended for 50,000 or fewer.

“Add vector search to an existing container” → Not supported: create a new container with the vector embedding policy and vector index. Trap: Set both policies when you create the container (the Python how-to says you can't modify them later; the vector store page says paths can be added or removed but settings can't be changed directly), and enable the feature on the account first (can take 15 minutes).

“VectorDistance query costs too many RUs” → Add TOP N and exclude the vector path from the regular index. Trap: Without TOP N the search returns many more results; an indexed vector path raises insert RU and latency.

“Python app must read changes for one partition key, at its own pace” → Change feed pull model (query_items_change_feed with partition_key). Trap: The change feed processor is .NET and Java only and can't process a single partition key.

“Processor delegate throws an unhandled exception” → The same batch is retried from the last saved lease point. Trap: The processor retries the batch; write failed items to an errored-message queue so it doesn't get stuck.

“Need deletes and every intermediate change in the feed” → All versions and deletes mode (requires continuous backups). Trap: Latest version mode doesn't capture deletes and shows only the latest change.

Sources

Checked against Microsoft Learn on November 13, 2026.

← AI Data Services overviewPostgreSQL & pgvector →