Overview of Indexing Policies

Learn how to create indexing policies on a Cosmos DB container to improve query performance and reduce costs.

Indexing in Cosmos DB

By default, Cosmos DB indexes every property in a document. This approach improves efficiency when we use the WHERE or ORDER BY clauses on a single property.

Property path mapping

It’s out of the scope of this lesson to teach how Cosmos DB creates indexes, but it’s interesting to have a small overview.

When requesting the creation of an item, the database does the following:

  • Projects the item as a JSON document.

  • Converts the item into a tree and updates indexes.

This process helps the engine extract the path of a value by traversing the tree and concatenating each node label.

For example, take a look at the following document:

{
"title": "Game A",
"price": 19.99,
"developer": {
"name": "Publisher A"
"country": "US"
}
}
Example of a "game" document

It is converted into the following tree:

Press + to interact
Tree representation of a game document
Tree representation of a game document

This structure makes it easy to extract the following paths during queries:

  • /title: Game A

  • /price: 19.99

  • /developer/name: Publisher A

  • /developer/country: US

Type of indexes

There are three types of indexes we can define:

  • Range index

  • Spatial index

  • Composite index

Range index

By default, this is the index type applied to any string or number property.

Cosmos DB uses an ordered tree to create this index, similar to SQL indexes. We can imagine them as the union of all document trees, where each node contains the ID of the source document.

Press + to interact
Tree representation of an index from two documents
Tree representation of an index from two documents

With this representation, finding the documents that match the query is fast. Let’s see an example:

SELECT * FROM games WHERE c.developer.country = 'UK'
Getting all games developed in UK
...