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.
| Task | Call | Notes |
|---|---|---|
| Install | pip install azure-cosmos and pip install azure-identity | Both packages are listed in requirements.txt in the quickstart. |
| Authenticate | credential = 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 database | client.get_database_client("cosmicworks") | Returns a DatabaseProxy. |
| Get a container | database.get_container_client("products") | Returns a ContainerProxy: read, update and delete on the container or its items. |
| Create or replace an item | container.upsert_item(new_item) | Upserts: replaces the item if it already exists. |
| Point read | container.read_item(item="<id>", partition_key="<key>") | Needs both the id and the partition key. |
| Query | container.query_items(query=..., parameters=[...], enable_cross_partition_query=False) | Parameterized: SELECT * FROM products p WHERE p.category = @category. |
- Point reads cost fewer RUs than queries. Reading one item of about 1 KB by ID and partition key uses one request unit.
- The
PartitionKeyclass represents a logical partition key and is required for many common operations and queries. - The number of RUs for a given operation over a given dataset is deterministic: the same query on the same data always costs the same RUs. Read the request charge from the response header.
Indexing policy and RU cost
| Setting | Rule |
|---|---|
| Default policy | Indexes every property of every item and enforces range indexes for any string or number. |
| Mode Consistent | Index updated synchronously as items are created, updated or deleted; read queries use the account's consistency. |
| Mode None | Indexing disabled. Used for a pure key-value store, or to speed up bulk operations; then set Consistent again and watch IndexTransformationProgress. |
| Lazy mode | Can give inconsistent or incomplete query results. New containers can't select it. |
| Property paths | Scalar path ends with /?; array elements use /[]; /* matches everything below a node. |
| Root path | Every policy must include /* as an included or an excluded path. Including it and excluding what you don't need is the recommended approach. |
| Precedence | If included and excluded paths conflict, the more precise path wins. |
| System properties | id and _ts are indexed in Consistent mode; _etag is excluded by default. |
Composite indexes
ORDER BYon two or more properties requires a composite index. The path sequence and the ASC/DESC order must match theORDER BY; the exact opposite order on all paths also works.- With
(name ASC, age ASC):ORDER BY c.name DESC, c.age DESCis supported;ORDER BY c.age ASC, c.name ASCandORDER BY c.name ASC, c.age DESCare not. - For filters: equality properties go first in the composite index, and a property with a range filter (
>,<,<=,>=,!=) goes last. Each composite index can optimize only one range filter, so two range filters need two composite indexes. - Composite paths can't use the
/*wildcard; each has an implicit/?at the end. - A new composite index doesn't help until its build finishes: until then queries use the existing range indexes.
What drives RU charges
- Item size, item property count and the number of indexed properties: fewer indexed paths means lower write RU and latency.
- Consistency: strong and bounded staleness cost about two times more RUs for reads.
- Query shape: number of results, predicates, user-defined functions, source data size and projections.
- Throughput modes: provisioned (increments of 100 RU/s), serverless, autoscale.
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.
| Level | Guarantee | Reads |
|---|---|---|
| Strong | Linearizability: reads return the most recent committed version. | Two replicas (local minority); about 2x RU cost |
| Bounded staleness | Lag 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 |
| Session | Within one client session: read-your-writes and write-follows-reads. Uses a session token. Most widely used level. | Single replica |
| Consistent prefix | Reads never see out-of-order writes; a transaction's writes are visible together. | Single replica |
| Eventual | Weakest: a read can return older values than ones read before. No ordering guarantee. | Single replica |
- Session tokens are partition-bound. A client that hasn't written to a physical partition has no token for it, so reads from it behave like Eventual until a write builds the cache.
- After you change the account default, restart the application so the SDK instance is recreated and uses the new default.
- Overriding the level applies only to reads within the SDK client. Strong accounts still write synchronously to every region.
- Accounts with multiple write regions can't use strong consistency.
- Bounded staleness minimum K and T: 10 writes or 5 seconds (single region); 100,000 writes or 300 seconds (multiple regions).
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 field | Value |
|---|---|
path | Property that holds the vector (required). One policy per path. |
dataType | float32, float16, int8 or uint8. float16 can cut vector storage by 50% with some accuracy loss. |
dimensions | Length of each vector. Default 1536. |
distanceFunction | cosine (default, -1 to +1, higher is more similar), dotproduct, euclidean (0 is most similar). |
| Vector index | Behavior | Max dimensions |
|---|---|---|
flat | Brute force, 100% recall. | 505 |
quantizedFlat | Brute force over compressed vectors; slightly lower accuracy. Recommended when 50,000 or fewer vectors are in scope. | 4096 |
diskANN | Approximate 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 |
quantizedFlatanddiskANNneed at least 1,000 vectors; with fewer, a full scan runs instead and RU charges might be higher.- Add the vector path to
excludedPathsof the indexing policy. Without it, vector inserts cost more RUs and latency. - Query with
VectorDistanceand always addTOP N:SELECT TOP 10 c.title, VectorDistance(c.contentVector, [1,2,3]) AS SimilarityScore FROM c ORDER BY VectorDistance(c.contentVector, [1,2,3]). - diskANN is approximate: the same query can return slightly different results. Need exact results: use
flat. RaisingsearchListSizeMultipliertrades latency and RU for recall. - Not supported on accounts with Shared Throughput. Once enabled on a container, vector indexing and search can't be disabled.
| Python call | Purpose |
|---|---|
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
- The change feed is a persistent record of changes to a container, in the order the changes occur. It is enabled by default on all accounts.
- Latest version mode: inserts and updates only; no indication which; deletes aren't captured. All versions and deletes mode: creates, updates, deletes and TTL expirations, including intermediate changes; requires continuous backups on the account.
- Order is guaranteed per partition key, not across partition key values.
- The only cost of the change feed is the lease container's provisioned throughput and the RUs of each request.
| Change feed processor | Pull model | |
|---|---|---|
| SDKs | .NET V3 and Java only | Python and Node.js (the processor library is only for .NET and Java) |
| Progress tracking | Lease documents in a lease container | Continuation token (in memory or saved by you) |
| Delivery | Automatic checkpointing, at-least-once | You manage checkpoints |
| Polling | Automatic, WithPollInterval | Manual |
| One partition key only | Not supported | Yes |
| Parallelism | Automatic across instances | Manual, with FeedRange |
Processor components and life cycle
- Monitored container: source of the changes. Lease container: state storage, same account or another. Compute instance: hosts the processor, has a unique instance name. Delegate: your code for each batch.
- Life cycle: read the change feed; if no changes, sleep and read again; if changes, send them to the delegate; when the delegate succeeds, update the lease store.
- Unhandled exception in the delegate: the same batch is sent again from the last saved point. Write failed items to an errored-message queue so the processor doesn't get stuck.
- Scaling out: same
processorName, same lease container configuration, a different instance name each. A lease is owned by one instance at a time, so instances shouldn't outnumber leases. - Use a global endpoint, not a regional one; leases are scoped to the endpoint. Register at least
WithErrorNotification.
| Python pull-model call | Purpose |
|---|---|
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
| Task | Azure CLI | PowerShell |
|---|---|---|
| Enable NoSQL vector search on an account | az 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
- Quickstart: Azure SDK for Python and Azure Cosmos DB
- Consistency level choices
- How to manage consistency levels
- Indexing policies
- Request Units as a throughput and performance currency
- Integrated vector store
- Index and query vector data in Python
- Work with the change feed
- Change feed processor
- Change feed pull model
Checked against Microsoft Learn on November 13, 2026.