Lesson 3 of 4 Developing with Azure Cosmos DB for NoSQL

Optimizing Request Units with Indexing Policies

This lesson explains how indexing affects cost, how to include and exclude paths, when composite indexes are needed, and other ways to reduce RU consumption.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain the effect of the default indexing policy on writes.
  • Describe opt-in and opt-out indexing strategies.
  • Identify when a composite index is required.
  • Describe techniques that lower RU consumption.

How indexing affects cost

Every container has an indexing policy. The default policy uses consistent indexing mode and indexes every path in every item (/*), except the system _etag property. This makes any query possible without design work, and queries that filter on indexed properties are efficient because the engine reads the index rather than scanning items.

The cost appears on writes. Each write updates the index entries for every indexed property, so an item with many properties, or with large nested arrays, costs more RUs to write and occupies more storage. For write-heavy containers, such as event or telemetry data, and for items that carry large values that are never queried, such as embeddings or long text, a tailored policy can cut write RUs substantially.

True or false

Indexing and cost

Exam skills 2.1.2

Decide whether each statement about the default indexing policy is true.

Log in to try this activity Interactive activities are free with an account.

Included and excluded paths

An indexing policy lists includedPaths and excludedPaths. Path syntax uses /? for a scalar value and /* for everything below a path. Two strategies are common: opt out, which includes /* and excludes a few large or unqueried paths, and opt in, which excludes /* and includes only the paths that queries use. Opt-out is safer when queries may change, because new properties are indexed automatically.

{
  "indexingMode": "consistent",
  "automatic": true,
  "includedPaths": [ { "path": "/*" } ],
  "excludedPaths": [
    { "path": "/\"_etag\"/?" },
    { "path": "/description/?" },
    { "path": "/embedding/*" }
  ],
  "compositeIndexes": [
    [ { "path": "/category", "order": "ascending" }, { "path": "/price", "order": "descending" } ]
  ]
}

This policy keeps everything indexed except the long description text and the embedding array, which no query filters on; the embedding is served by a separate vector index, described in the next module. Excluding a path does not stop it from being returned in results; it only means that filters and sorts on it cannot use the index.

The following diagram shows which fields of a product catalog stay indexed and the resulting Cosmos DB indexing policy.

An opt-out indexing policy for the product catalog. Category, brand and price stay indexed for the queries, with a composite index on category and price for the filtered sort. The 1,536-number embedding and the 5 KB description are excluded from the range index, which removes most index updates per write; the embedding is searched through a vector index instead.
The vector index for the embedding is defined separately.
Scenario questions

Shaping the indexing policy

Exam skills 2.1.2

Choose the indexing policy change that fits each requirement.

Log in to try this activity Interactive activities are free with an account.

Composite indexes

A query with ORDER BY on a single property uses the ordinary range index. A query that sorts on two or more properties requires a composite index that lists them in the same order and directions (or all reversed); without it, the query fails. Composite indexes also make queries that filter on one property and sort on another, or filter on several properties, cheaper.

The composite index in the previous policy serves SELECT * FROM c WHERE c.category = @cat ORDER BY c.category ASC, c.price DESC. Index order matters: an index on (category, price) does not serve a sort on (price, category). Composite indexes add write cost like any index, so they are added for specific, frequent queries.

Changing a policy and measuring the effect

An indexing policy can be changed at any time, and the service transforms the index online in the background using spare throughput. Queries keep working during the transformation, but results that depend on newly added paths may be incomplete until it finishes. The none indexing mode disables indexing entirely, which suits a container used only for point reads as a key-value store.

Cost is measured rather than guessed. The request charge header shows the RUs of each operation, and the SDK can return index metrics for a query (populate_index_metrics=True), which list the indexes that were used and those that would help. Other RU reductions complement indexing.

  • Use point reads instead of queries when the id and partition key are known.
  • Include the partition key in queries to avoid fan-out.
  • Project only needed properties and keep items small; store large blobs in Blob Storage.
  • Use patch operations instead of replacing whole items.
  • Set a time to live (TTL) on transient data so that it expires without delete operations.
Select all that apply

Lowering RU charges

Exam skills 2.1.2

Identify the changes that lower request unit consumption.

Log in to try this activity Interactive activities are free with an account.
Worked example

Reducing write cost for a product catalog

A product container stores 2 million items, each with a 1,536-dimension embedding, a 5 KB description and about 20 attributes. Queries filter on category, brand and price and sort by price within a category. Product updates cost about 40 RUs each, and the team wants to cut write cost without slowing queries.

The default policy indexes every element of the embedding array and every word-bearing description string, although no query filters on them. Changing to an opt-out policy that excludes /embedding/* and /description/? removes most index updates per write. A composite index on category ascending and price ascending keeps the filtered sort efficient. The embedding is then searched through a vector index, not the range index.

Setting the indexing mode to none would make every filter a full scan, or fail. Excluding /* without including category, brand and price would slow the catalog queries. Raising throughput would pay for the waste rather than remove it.

Check yourself

A query sorts on c.category and c.price and fails. What does the container need?

Show answer

A composite index on category and price in the same order and directions as the ORDER BY clause (or all reversed).

Exam Tips

Remember for the exam

  • The default policy indexes every path; exclude large or unqueried paths to cut write RUs.
  • ORDER BY on several properties requires a matching composite index.
  • Policy changes run online; new paths may give incomplete results until the transformation ends.
  • Measure with the request charge header and query index metrics.