Overview of Indexing Policies
Explore the fundamentals of indexing policies in Azure Cosmos DB. Understand how default and custom range, spatial, and composite indexes improve query speed and manage resource consumption. Learn methods to update policies using Azure portal and CLI, enhancing your data modeling skills.
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"}}
It is converted into the following tree:
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.
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'