Launch price: every exam for $29.99 a year, for the first 300 buyers. See the price

CertStreak
Menu

Optimize query performance and Request Units (RUs) consumption by using indexing policies and consistency levels

A worked example

Single answer

An AI document search application stores items in an Azure Cosmos DB for NoSQL container. The container's indexing policy is shown in the exhibit.

A new feature runs the following query, which sorts first by relevance score and then by upload date:

SELECT * FROM c
ORDER BY c.relevanceScore DESC, c.uploadDate ASC

The query fails with an error stating that a composite index is required.

{ "indexingMode": "consistent", "includedPaths": [ { "path": "/*" } ], "excludedPaths": [ { "path": "/"_etag"/?" } ], "compositeIndexes": [ [ { "path": "/relevanceScore", "order": "descending" }, { "path": "/uploadDate", "order": "descending" } ] ] }

Which composite index should you add to the indexing policy so that the query runs?

Choose one answer
Why

A multi-property ORDER BY needs a composite index that matches its property sequence and sort directions. A composite index also serves the exact opposite direction on every path. That is why the existing DESC/DESC index works for DESC/DESC and ASC/ASC sorts but not for DESC/ASC. The mixed order needs a separate composite index on relevanceScore descending, then uploadDate ascending. The range indexes created by /* are not enough for this multi-property sort.

  • Not correct: /uploadDate descending, then /relevanceScore ascending. The index starts with upload date, but the query sorts by relevance score first. The property sequence does not match the ORDER BY clause.
  • Correct: /relevanceScore descending, then /uploadDate ascending. This matches the exact property sequence and the mixed sort directions of the ORDER BY clause, which is what a composite index must do to serve the query.
  • Not correct: /uploadDate ascending, then /relevanceScore descending. The properties are in the wrong sequence. A composite index must list the properties in the same order as the ORDER BY clause.
  • Not correct: /relevanceScore ascending, then /uploadDate ascending. This index serves only ASC/ASC sorts and their full opposite, DESC/DESC. It does not serve the mixed DESC/ASC order that the query uses.

Practise this topic until it's automatic.

Ten questions a day, every answer explained, and misses that come back until you beat them.

Start free