Cosmos DB Interview Questions and Answers Part 5 - Queries and Indexing

Cosmos DB Interview Q&A · Part 5 of 10

In this post we are going to cover queries and indexing in Azure Cosmos DB. These are 7 real Cosmos DB interview questions for data engineers, asked the way they come up on a real project, and the last one is a scenario: the product search page is slow and costs too many RUs, and we have to investigate and fix it.

The API for NoSQL lets us query JSON items with a SQL-like language, and every property is indexed by default. Interviewers ask about this because it looks like plain SQL, but it isn't. The query you write and the indexing policy behind it decide what each query costs, and that is where real projects spend their RUs.

Part 5 of the Real Time Azure Cosmos DB Interview Questions and Answers series on TechBrothersIT.

The short answer

Say this first

The API for NoSQL queries JSON items with a SQL-like language, best with parameters and the partition key. Every property is indexed by default; sorting on two fields needs a composite index, and excluding unused paths makes writes cheaper. JOIN works inside one item; aggregate and GROUP BY inside one partition, and page with continuation tokens.

Let's set up the project

We run the official Azure Cosmos DB Linux emulator locally, and small Python scripts that use the azure-cosmos client, so every output is real. Features the emulator doesn't support are shown as code. common.py creates the client from the COSMOS_ENDPOINT and COSMOS_KEY environment variables, creates the shop database, and has a small helper for a products container partitioned by /category. products.json holds nine products in three categories, each with tags, an array of variants, and a long description.

common.py
import os
from azure.cosmos import CosmosClient, PartitionKey

client = CosmosClient(os.environ["COSMOS_ENDPOINT"],
                      credential=os.environ["COSMOS_KEY"])
db = client.create_database_if_not_exists("shop")


def products(name="products", **options):
    """A products container partitioned by category."""
    return db.create_container_if_not_exists(
        name, partition_key=PartitionKey(path="/category"), **options)
products.json
[
 {"id": "g1", "category": "games", "name": "Galaxy Quest",
  "price": 39.99, "rating": 4.7, "tags": ["space", "family"],
  "variants": [{"color": "blue", "stock": 12},
               {"color": "red", "stock": 0}],
  "description": "A space adventure board game for the whole family"},
 {"id": "g2", "category": "games", "name": "Dragon Dice",
  "price": 14.5, "rating": 4.2, "tags": ["dice", "party"],
  "variants": [{"color": "green", "stock": 30}],
  "description": "A fast dice game for parties"},
 {"id": "g3", "category": "games", "name": "Castle Builder",
  "price": 54.9, "rating": 4.7, "tags": ["strategy", "family"],
  "variants": [{"color": "gray", "stock": 3},
               {"color": "gold", "stock": 1}],
  "description": "Build a castle together: a strategy game for families"},
 {"id": "g4", "category": "games", "name": "Card Clash",
  "price": 9.99, "rating": 3.9, "tags": ["cards"],
  "variants": [{"color": "black", "stock": 50}],
  "description": "A card battle game for two players"},
 {"id": "g5", "category": "games", "name": "Pixel Racer",
  "price": 24.99, "rating": 4.1, "tags": ["racing", "family"],
  "variants": [{"color": "yellow", "stock": 8}],
  "description": "A racing game the whole family can play"},
 {"id": "t1", "category": "toys", "name": "Robot Kit",
  "price": 29.5, "rating": 4.5, "tags": ["stem"],
  "variants": [{"color": "silver", "stock": 7},
               {"color": "orange", "stock": 2}],
  "description": "Build and code your own robot"},
 {"id": "t2", "category": "toys", "name": "Bouncy Ball",
  "price": 3.5, "rating": 4.0, "tags": ["outdoor"],
  "variants": [{"color": "red", "stock": 40}],
  "description": "A ball that bounces higher than you think"},
 {"id": "b1", "category": "books", "name": "Space Atlas",
  "price": 19.25, "rating": 4.6, "tags": ["space"],
  "variants": [{"color": "white", "stock": 5}],
  "description": "Maps of the planets and the stars"},
 {"id": "b2", "category": "books", "name": "Puzzle Book",
  "price": 7.75, "rating": 4.3, "tags": ["puzzles"],
  "variants": [{"color": "white", "stock": 20}],
  "description": "One hundred puzzles for rainy days"}
]

Question 1: A teammate asks how querying works in the NoSQL API. How do you explain the SQL-like query language?

We write SELECT, FROM, WHERE and ORDER BY against JSON items. FROM c means the items of one container, c is only an alias, and dot paths reach nested properties. The results come back as JSON.

Let's try it. First load.py loads the nine products into a container partitioned by category. Then query.py asks for the top three games under fifty, with only the name, price and rating, highest price first. The values come in as parameters, @cat and @max, never glued into the string. And the partition key, games, routes the query to one logical partition. At the end it also runs a query with LIMIT and no OFFSET. We run python load.py and python query.py.

load.py
import json
from common import products

container = products()
items = json.load(open("products.json"))
for item in items:
    container.upsert_item(item)
cats = sorted({item["category"] for item in items})
print("loaded", len(items), "products in", len(cats), "categories:",
      cats)
query.py
import json
from azure.cosmos.exceptions import CosmosHttpResponseError
from common import products

container = products()
sql = ("SELECT TOP 3 c.name, c.price, c.rating FROM c"
       " WHERE c.category = @cat AND c.price < @max"
       " ORDER BY c.price DESC")
params = [{"name": "@cat", "value": "games"},
          {"name": "@max", "value": 50}]
for row in container.query_items(sql, parameters=params,
                                 partition_key="games"):
    print(row)

bad = "SELECT c.name FROM c ORDER BY c.price DESC LIMIT 3"
try:
    list(container.query_items(bad, partition_key="games"))
except CosmosHttpResponseError as e:
    error = json.loads(e.http_error_message)["errors"][0]
    print(e.status_code, error["message"])
Terminal
$ python load.py
loaded 9 products in 3 categories: ['books', 'games', 'toys']
$ python query.py
{'name': 'Galaxy Quest', 'price': 39.99, 'rating': 4.7}
{'name': 'Pixel Racer', 'price': 24.99, 'rating': 4.1}
{'name': 'Dragon Dice', 'price': 14.5, 'rating': 4.2}
400 Syntax error, incorrect syntax near 'LIMIT'.

The load prints loaded 9 products in 3 categories: ['books', 'games', 'toys']. The query returns Galaxy Quest at 39.99, Pixel Racer at 24.99 and Dragon Dice at 14.5.

The last line is the important one. It's SQL-like, not full SQL. A LIMIT without OFFSET is rejected with 400 Syntax error, incorrect syntax near 'LIMIT'. So use TOP, or OFFSET and LIMIT together.

Real project

Always pass parameters and the partition key. Parameters keep user input out of the query text, and the partition key keeps the query on one partition.

Question 2: A query that filters on two fields is expensive. How does indexing work, and what is the default policy?

Every property of every item is indexed by default, with no schema and no secondary indexes. It's an inverted index: each path and value points to its items, so both filters use the index.

Think of it like this. /category = "games" points to g1, g2, g3, g4 and g5. /price below 50 points to g1, g2, g4, g5 and more. Both filters together give g1, g2, g4 and g5.

Let's read the default policy from the container's properties. We run python index.py.

index.py
from common import products

policy = products().read()["indexingPolicy"]   # container properties
print("indexingMode:", policy["indexingMode"],
      "| automatic:", policy["automatic"])
print("includedPaths:", [p["path"] for p in policy["includedPaths"]])
print("excludedPaths:", [p["path"] for p in policy["excludedPaths"]])
Terminal
$ python index.py
indexingMode: consistent | automatic: True
includedPaths: ['/*', '/"_ts"/?']
excludedPaths: ['/"_etag"/?']

It's consistent, automatic is True, and /* is included, so every path. The ETag is excluded, and the emulator also lists the /"_ts"/? path.

Strings and numbers get range indexes. How a filter uses them drives the cost:

How the filter uses the indexExamplesCost
index seek= and INlowest
precise index scanranges, STARTSWITHlow
full index scanCONTAINS, ENDSWITH, LIKEhigh
full scanUPPER, LOWERhighest

So for an expensive two-field filter, check these:

  • Partition key in the filter? - or every partition is read
  • A function forcing a scan? - LOWER, CONTAINS
  • Whole documents? - project the fields you need
  • Equality plus range? - a composite index on both fields

Index metrics show which indexes were used. On Azure we ask for them like this:

metrics.py (Azure, not run)
# Azure: ask for index metrics on a query (the emulator
# returns an empty value, so this is shown as code)
rows = list(container.query_items(sql, parameters=params,
            partition_key="games",
            populate_index_metrics=True))
h = container.client_connection.last_response_headers
print(h["x-ms-request-charge"])            # RU, last page
print(h["x-ms-cosmos-index-utilization"])  # used, potential indexes
Emulator note

The emulator stores the policy but doesn't enforce it, and charges 1 RU for everything. Index effects and RU numbers come from Azure.

Question 3: Someone wants to sort on two fields and the query fails. What is a composite index?

A composite index indexes several properties together, in a set order. Microsoft's rule is clear: an ORDER BY on two or more properties always needs one. Without it, Azure rejects the query.

QueryIndex it needs
ORDER BY c.pricethe default range index
ORDER BY c.rating DESC, c.price ASCcomposite (/rating descending, /price ascending)
properties per composite indexup to 8

Let's create a container with a composite index: rating descending, then price ascending. Then we load the products and order the games by rating, highest first, breaking ties by the lowest price. We run python composite.py.

composite.py
import json
from common import products

ORDER = [{"path": "/rating", "order": "descending"},
         {"path": "/price", "order": "ascending"}]
container = products("products_sorted",
                     indexing_policy={"compositeIndexes": [ORDER]})
for item in json.load(open("products.json")):
    container.upsert_item(item)

policy = container.read()["indexingPolicy"]
print("compositeIndexes:", [[(p["path"], p["order"]) for p in index]
                            for index in policy["compositeIndexes"]])
sql = ("SELECT c.name, c.rating, c.price FROM c"
       " ORDER BY c.rating DESC, c.price ASC")
for row in container.query_items(sql, partition_key="games"):
    print(row)
Terminal
$ python composite.py
compositeIndexes: [[('/rating', 'descending'), ('/price', 'ascending')]]
{'name': 'Galaxy Quest', 'rating': 4.7, 'price': 39.99}
{'name': 'Castle Builder', 'rating': 4.7, 'price': 54.9}
{'name': 'Dragon Dice', 'rating': 4.2, 'price': 14.5}
{'name': 'Pixel Racer', 'rating': 4.1, 'price': 24.99}
{'name': 'Card Clash', 'rating': 3.9, 'price': 9.99}

The container accepts it, and reading the policy back shows [('/rating', 'descending'), ('/price', 'ascending')]. Galaxy Quest and Castle Builder both have 4.7, so the cheaper one, Galaxy Quest at 39.99, comes first.

The emulator doesn't enforce indexes, so here the query would run even without one. The failure only shows on Azure, so it's code:

Azure behavior (not run)
# Azure, container WITHOUT a matching composite index:
#   SELECT c.name, c.rating, c.price FROM c
#   ORDER BY c.rating DESC, c.price ASC
#   -> the query fails: an ORDER BY on two or more
#      properties always needs a composite index
# the index must match the ORDER BY: same properties,
#   same order, same directions (or all reversed)
# max 8 properties per composite index

Match the index to the ORDER BY: same properties, same order, same directions, or all reversed. A composite index holds up to 8 properties, and filtering plus sorting may need more than one.

Tip

Add new indexes before the release. Adding one takes time, removing one is immediate.

Question 4: Writes are expensive because every field is indexed. How do you tune the indexing policy?

Index only what you query. Every indexed path adds work to every write, and Microsoft says indexing only the properties you filter on can make a huge difference to write RUs. So exclude the paths no query filters or sorts on.

Our products carry a long description that no query filters on. Let's replace the policy: /* stays included and /description/* is excluded. We run python tune.py.

tune.py
from azure.cosmos import PartitionKey
from common import db, products

container = products()
policy = {"indexingMode": "consistent", "automatic": True,
          "includedPaths": [{"path": "/*"}],
          "excludedPaths": [{"path": "/description/*"}]}
db.replace_container(container,
                     partition_key=PartitionKey(path="/category"),
                     indexing_policy=policy)

policy = container.read()["indexingPolicy"]
print("includedPaths:", [p["path"] for p in policy["includedPaths"]])
print("excludedPaths:", [p["path"] for p in policy["excludedPaths"]])
Terminal
$ python tune.py
includedPaths: ['/*', '/"_ts"/?']
excludedPaths: ['/description/*', '/"_etag"/?']

Reading it back shows the new path: the excluded paths are now ['/description/*', '/"_etag"/?'], and /* is still included.

The other style is opt-in: exclude /* and include only the paths you query.

opt-in policy (JSON)
{
  "indexingMode": "consistent",
  "includedPaths": [{"path": "/category/?"},
                    {"path": "/price/?"},
                    {"path": "/rating/?"}],
  "excludedPaths": [{"path": "/*"}]
}

It's the cheapest for writes, but every new query field needs a policy change first.

A few rules about changing the policy:

  • Online change - writes are not interrupted
  • Remove an index - immediate; adding one takes time
  • indexingMode none - no time to live on the container
Measure it

The emulator stores this policy but doesn't apply it, so measure write RUs on Azure, before and after, with real documents.

Question 5: A teammate asks about JOIN in Cosmos DB. How does it work inside one document?

A JOIN in Cosmos DB is a self-join: it pairs an item with the elements of an array inside that same item. It can't join two items or two containers. Think of it as unnesting the array.

For example, Castle Builder has two variants, gray and gold. JOIN v IN p.variants gives one row per element, so two rows: gray with stock 3 and gold with stock 1.

Let's count it. join.py counts the games, counts the rows after the JOIN, filters on stock below 5, and then tries EXISTS. We run python join.py.

join.py
from common import products

container = products()


def query(sql, **values):
    params = [{"name": "@" + k, "value": v}
              for k, v in values.items()]
    return list(container.query_items(sql, parameters=params,
                                      partition_key="games"))


print("products:", query("SELECT VALUE COUNT(1) FROM p"))
print("rows after the JOIN:", query(
    "SELECT VALUE COUNT(1) FROM p JOIN v IN p.variants"))
for row in query("SELECT p.name, v.color, v.stock FROM p"
                 " JOIN v IN p.variants WHERE v.stock < @low", low=5):
    print(row)
print("EXISTS:", query("SELECT VALUE p.name FROM p WHERE EXISTS("
                       "SELECT VALUE v FROM v IN p.variants"
                       " WHERE v.stock < @low)", low=5))
Terminal
$ python join.py
products: [5]
rows after the JOIN: [7]
{'name': 'Galaxy Quest', 'color': 'red', 'stock': 0}
{'name': 'Castle Builder', 'color': 'gray', 'stock': 3}
{'name': 'Castle Builder', 'color': 'gold', 'stock': 1}
EXISTS: ['Galaxy Quest', 'Castle Builder']

There are [5] products, but rows after the JOIN: [7]. The five games have seven variants between them, and the JOIN makes a complete cross product of each product with its own variants.

The filter returns the low stock rows: the red Galaxy Quest with 0, and two Castle Builder variants, gray with 3 and gold with 1. Castle Builder appears twice, once per matching variant. When you want each product only once, use EXISTS with a subquery instead. It returns ['Galaxy Quest', 'Castle Builder'], one row each.

Pitfall

Two JOINs over two big arrays: the cross product multiplies, and so does the cost. The limit is 10 JOINs per query, and you rarely need more than one.

Question 6: A report needs totals by category. How do aggregates, GROUP BY and continuation tokens work?

COUNT, SUM, AVG, MIN and MAX work as in SQL, and GROUP BY groups rows. Keep them inside one partition key: the Python SDK doesn't support GROUP BY across partitions.

Let's build it. agg.py creates a sales container partitioned by /storeId and adds ten sales for two stores. Then it runs the totals and a GROUP BY by category, both for store-1. We run python agg.py.

agg.py
from azure.cosmos import PartitionKey
from common import db

sales = db.create_container_if_not_exists(
    "sales", partition_key=PartitionKey(path="/storeId"))
rows = [("store-1", "games", 40.5), ("store-1", "books", 12.25),
        ("store-1", "games", 25.75), ("store-1", "toys", 8.5),
        ("store-1", "books", 18.5), ("store-1", "games", 30.25),
        ("store-1", "toys", 11.75), ("store-1", "books", 9.5),
        ("store-2", "games", 22.5), ("store-2", "toys", 15.25)]
for n, (store, category, amount) in enumerate(rows, start=1):
    sales.upsert_item({"id": f"sale-{n}", "storeId": store,
                       "category": category, "amount": amount})

totals = ("SELECT COUNT(1) AS sales, SUM(c.amount) AS total,"
          " AVG(c.amount) AS average FROM c")
print(list(sales.query_items(totals, partition_key="store-1")))
by_category = ("SELECT c.category, COUNT(1) AS sales,"
               " SUM(c.amount) AS total FROM c GROUP BY c.category")
for row in sales.query_items(by_category, partition_key="store-1"):
    print(row)
Terminal
$ python agg.py
[{'sales': 8, 'total': 157, 'average': 19.625}]
{'category': 'games', 'sales': 3, 'total': 96.5}
{'category': 'books', 'sales': 3, 'total': 40.25}
{'category': 'toys', 'sales': 2, 'total': 20.25}

For store one we get 8 sales, a total of 157 and an average of 19.625. GROUP BY category, in the same partition, gives games 96.5, books 40.25 and toys 20.25.

All stores at once is code. The emulator has one physical partition, so it can't show the limit. On Azure, loop over the stores and add up in Python:

all stores (Azure, not run)
# All stores at once: cross-partition GROUP BY.
# Not supported in the Python SDK. The emulator has one
# physical partition, so it can't show this limit.
totals = {}
for store in ["store-1", "store-2"]:        # one partition each
    for row in sales.query_items(by_category, partition_key=store):
        totals[row["category"]] = (totals.get(row["category"], 0)
                                   + row["total"])

For a big report, query a Fabric mirror instead.

Big results come in pages. page.py reads the store one sales with max_item_count=3, saves the continuation token after page one, and then starts a new query from that token. We run python page.py.

page.py
from common import db

sales = db.get_container_client("sales")
sql = "SELECT c.id, c.amount FROM c"
pages = sales.query_items(sql, partition_key="store-1",
                          max_item_count=3).by_page()
first = list(next(pages))
token = pages.continuation_token            # a bookmark: save it
print("page 1:", len(first), "items | token is not None:",
      token is not None)

rest = sales.query_items(sql, partition_key="store-1",
                         max_item_count=3).by_page(token)  # resume
for n, page in enumerate(rest, start=2):
    print(f"page {n}:", len(list(page)), "items | token is not None:",
          rest.continuation_token is not None)
Terminal
$ python page.py
page 1: 3 items | token is not None: True
page 2: 3 items | token is not None: True
page 3: 2 items | token is not None: False

Page one has 3 items and a token. The new query, resumed from that token, returns 3, then 2, and then token is not None: False: the end.

Remember

Tokens are stateless bookmarks you can save and resume from later. They don't work with GROUP BY, or DISTINCT without ORDER BY, and a page can be empty, so loop until the token is None.

Scenario 7: The product search page is slow and costs too many RUs. How do you investigate and fix it?

Measure first. On Azure, read the RU charge of the search query from the response header, and turn on index metrics and query advice. Then walk the checklist.

Let's look at the old query. It does it all wrong: SELECT *, no partition key, and CONTAINS on LOWER of the description.

before.py (the slow query, not run)
# before: the search page query
sql = ("SELECT * FROM c"
       " WHERE CONTAINS(LOWER(c.description), @word)"
       " ORDER BY c.rating DESC, c.price ASC")
rows = container.query_items(sql, parameters=params,
                             enable_cross_partition_query=True)
# SELECT *       -> whole documents for a list page
# LOWER          -> full scan
# CONTAINS       -> full index scan
# no partition key -> every physical partition

LOWER is a full scan, CONTAINS a full index scan, and without the partition key it pays 2 to 3 RUs per physical partition. Here is the checklist:

  • Measure - RU charge from the response header, on Azure
  • Index metrics and query advice - which indexes were used, what to change
  • Partition key in the filter? - or 2-3 RUs per physical partition to fan out
  • Scans? - LOWER, UPPER, CONTAINS: prefer =, STARTSWITH, ARRAY_CONTAINS
  • SELECT *? - project the fields the page shows, TOP for one page
  • ORDER BY two fields? - a matching composite index

Now the fix. Filter on the partition key, category. Use ARRAY_CONTAINS on the tags, which uses the index. Return only the fields the page shows, with TOP. And add a composite index on rating, then price. We run python search.py.

search.py
import json
from common import products

ORDER = [{"path": "/rating", "order": "descending"},
         {"path": "/price", "order": "ascending"}]
catalog = products("catalog", indexing_policy={
    "includedPaths": [{"path": "/*"}],
    "excludedPaths": [{"path": "/description/*"}],
    "compositeIndexes": [ORDER]})
for item in json.load(open("products.json")):
    catalog.upsert_item(item)

sql = ("SELECT TOP @n c.id, c.name, c.price, c.rating FROM c"
       " WHERE c.category = @cat AND ARRAY_CONTAINS(c.tags, @tag)"
       " ORDER BY c.rating DESC, c.price ASC")
params = [{"name": "@n", "value": 10},
          {"name": "@cat", "value": "games"},
          {"name": "@tag", "value": "family"}]
for row in catalog.query_items(sql, parameters=params,
                               partition_key="games"):
    print(row)
Terminal
$ python search.py
{'id': 'g1', 'name': 'Galaxy Quest', 'price': 39.99, 'rating': 4.7}
{'id': 'g3', 'name': 'Castle Builder', 'price': 54.9, 'rating': 4.7}
{'id': 'g5', 'name': 'Pixel Racer', 'price': 24.99, 'rating': 4.1}

It returns the three family games, best rated first, and the cheaper one first on a tie: Galaxy Quest at 39.99, Castle Builder at 54.9, then Pixel Racer at 24.99.

The RU saving must be measured on Azure, because the emulator charges 1 RU for everything:

measure.py (Azure, not run)
# Azure: measure the new query, then compare
rows = list(catalog.query_items(sql, parameters=params,
            partition_key="games",
            populate_index_metrics=True,
            populate_query_advice=True))
h = catalog.client_connection.last_response_headers
print(h["x-ms-request-charge"])   # RU of the last page
Free text

If users need real free text search, don't force it through CONTAINS. Use the built-in full text search with a full text index, or a search index fed by the change feed.

Key points to remember

  • A SQL-like language over JSON: parameters and the partition key in every query
  • Everything is indexed by default (consistent, /*): functions like LOWER force scans
  • Two-field ORDER BY needs a composite index; exclude unused paths for cheaper writes
  • JOIN works inside one item; EXISTS returns each item once
  • GROUP BY inside one partition; page with continuation tokens until there is none

The full script

This is a Python script that writes every file and runs every command above in order against the Cosmos DB emulator: start the emulator, run pip install azure-cosmos first, set COSMOS_ENDPOINT and COSMOS_KEY, and run it in an empty folder on a freshly started emulator.

Show the full script that writes the files and runs every step
Full script - writes the files and runs every step against the Cosmos DB emulator (pip install azure-cosmos), run it with Python
# ========================================================================
# Cosmos DB Interview Q&A #5 - Queries and indexing
# TechBrothersIT. Names and sample data are invented for teaching.
# Every step below was run on the official Azure Cosmos DB Linux emulator (vNext, Docker image)
# with azure-cosmos 4.17.1; the outputs in the video and the blog post are the real outputs.
# To run it yourself:
#   1. docker run -p 8081:8081 -p 1234:1234 mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:vnext-latest
#      and wait until its log says "Now listening on: http://0.0.0.0:8081".
#   2. pip install azure-cosmos
#   3. Set COSMOS_ENDPOINT=http://localhost:8081 and COSMOS_KEY to the emulator key
#      (C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==),
#      then run python CosmosDB_Interview_QA_05_Code.py. The scripts create their own databases and containers.
# Run it in an empty folder and on a freshly started emulator: it creates its files (and any local data
# files) there, and a second run on old data gives different output.
# Steps that restart the emulator say so in a comment: stop and start it by hand at that point.
# ========================================================================

import os, subprocess, time

def write(path, text):
    if text is None:
        if os.path.exists(path): os.remove(path)
        return
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(text.strip("\n") + "\n")

def run(cmd, expect_error=False, allow_error=False, env=None):
    print("\n$ " + cmd, flush=True)
    rc = subprocess.run(cmd, shell=True, env=dict(os.environ, **(env or {}))).returncode
    if rc != 0 and not (expect_error or allow_error):
        raise SystemExit("stopped: this command was expected to succeed")

# Step 0: the starting files
write('common.py', 'import os\nfrom azure.cosmos import CosmosClient, PartitionKey\n\nclient = CosmosClient(os.environ["COSMOS_ENDPOINT"],\n                      credential=os.environ["COSMOS_KEY"])\ndb = client.create_database_if_not_exists("shop")\n\n\ndef products(name="products", **options):\n    """A products container partitioned by category."""\n    return db.create_container_if_not_exists(\n        name, partition_key=PartitionKey(path="/category"), **options)\n')
write('products.json', """\
[
 {"id": "g1", "category": "games", "name": "Galaxy Quest",
  "price": 39.99, "rating": 4.7, "tags": ["space", "family"],
  "variants": [{"color": "blue", "stock": 12},
               {"color": "red", "stock": 0}],
  "description": "A space adventure board game for the whole family"},
 {"id": "g2", "category": "games", "name": "Dragon Dice",
  "price": 14.5, "rating": 4.2, "tags": ["dice", "party"],
  "variants": [{"color": "green", "stock": 30}],
  "description": "A fast dice game for parties"},
 {"id": "g3", "category": "games", "name": "Castle Builder",
  "price": 54.9, "rating": 4.7, "tags": ["strategy", "family"],
  "variants": [{"color": "gray", "stock": 3},
               {"color": "gold", "stock": 1}],
  "description": "Build a castle together: a strategy game for families"},
 {"id": "g4", "category": "games", "name": "Card Clash",
  "price": 9.99, "rating": 3.9, "tags": ["cards"],
  "variants": [{"color": "black", "stock": 50}],
  "description": "A card battle game for two players"},
 {"id": "g5", "category": "games", "name": "Pixel Racer",
  "price": 24.99, "rating": 4.1, "tags": ["racing", "family"],
  "variants": [{"color": "yellow", "stock": 8}],
  "description": "A racing game the whole family can play"},
 {"id": "t1", "category": "toys", "name": "Robot Kit",
  "price": 29.5, "rating": 4.5, "tags": ["stem"],
  "variants": [{"color": "silver", "stock": 7},
               {"color": "orange", "stock": 2}],
  "description": "Build and code your own robot"},
 {"id": "t2", "category": "toys", "name": "Bouncy Ball",
  "price": 3.5, "rating": 4.0, "tags": ["outdoor"],
  "variants": [{"color": "red", "stock": 40}],
  "description": "A ball that bounces higher than you think"},
 {"id": "b1", "category": "books", "name": "Space Atlas",
  "price": 19.25, "rating": 4.6, "tags": ["space"],
  "variants": [{"color": "white", "stock": 5}],
  "description": "Maps of the planets and the stars"},
 {"id": "b2", "category": "books", "name": "Puzzle Book",
  "price": 7.75, "rating": 4.3, "tags": ["puzzles"],
  "variants": [{"color": "white", "stock": 20}],
  "description": "One hundred puzzles for rainy days"}
]
""")

# Step 1: Load nine products, run a parameterized query on one partition, and see a syntax error
write('load.py', """\
import json
from common import products

container = products()
items = json.load(open("products.json"))
for item in items:
    container.upsert_item(item)
cats = sorted({item["category"] for item in items})
print("loaded", len(items), "products in", len(cats), "categories:",
      cats)
""")
write('query.py', """\
import json
from azure.cosmos.exceptions import CosmosHttpResponseError
from common import products

container = products()
sql = ("SELECT TOP 3 c.name, c.price, c.rating FROM c"
       " WHERE c.category = @cat AND c.price < @max"
       " ORDER BY c.price DESC")
params = [{"name": "@cat", "value": "games"},
          {"name": "@max", "value": 50}]
for row in container.query_items(sql, parameters=params,
                                 partition_key="games"):
    print(row)

bad = "SELECT c.name FROM c ORDER BY c.price DESC LIMIT 3"
try:
    list(container.query_items(bad, partition_key="games"))
except CosmosHttpResponseError as e:
    error = json.loads(e.http_error_message)["errors"][0]
    print(e.status_code, error["message"])
""")
run('python load.py')
run('python query.py')

# Step 2: Read the default indexing policy from the container properties
write('index.py', """\
from common import products

policy = products().read()["indexingPolicy"]   # container properties
print("indexingMode:", policy["indexingMode"],
      "| automatic:", policy["automatic"])
print("includedPaths:", [p["path"] for p in policy["includedPaths"]])
print("excludedPaths:", [p["path"] for p in policy["excludedPaths"]])
""")
run('python index.py')

# Step 3: A container with a composite index on rating descending, price ascending, and a two-field ORDER BY
write('composite.py', """\
import json
from common import products

ORDER = [{"path": "/rating", "order": "descending"},
         {"path": "/price", "order": "ascending"}]
container = products("products_sorted",
                     indexing_policy={"compositeIndexes": [ORDER]})
for item in json.load(open("products.json")):
    container.upsert_item(item)

policy = container.read()["indexingPolicy"]
print("compositeIndexes:", [[(p["path"], p["order"]) for p in index]
                            for index in policy["compositeIndexes"]])
sql = ("SELECT c.name, c.rating, c.price FROM c"
       " ORDER BY c.rating DESC, c.price ASC")
for row in container.query_items(sql, partition_key="games"):
    print(row)
""")
run('python composite.py')

# Step 4: Tune the indexing policy: exclude the description path
write('tune.py', """\
from azure.cosmos import PartitionKey
from common import db, products

container = products()
policy = {"indexingMode": "consistent", "automatic": True,
          "includedPaths": [{"path": "/*"}],
          "excludedPaths": [{"path": "/description/*"}]}
db.replace_container(container,
                     partition_key=PartitionKey(path="/category"),
                     indexing_policy=policy)

policy = container.read()["indexingPolicy"]
print("includedPaths:", [p["path"] for p in policy["includedPaths"]])
print("excludedPaths:", [p["path"] for p in policy["excludedPaths"]])
""")
run('python tune.py')

# Step 5: JOIN over the variants array inside each product, and EXISTS
write('join.py', """\
from common import products

container = products()


def query(sql, **values):
    params = [{"name": "@" + k, "value": v}
              for k, v in values.items()]
    return list(container.query_items(sql, parameters=params,
                                      partition_key="games"))


print("products:", query("SELECT VALUE COUNT(1) FROM p"))
print("rows after the JOIN:", query(
    "SELECT VALUE COUNT(1) FROM p JOIN v IN p.variants"))
for row in query("SELECT p.name, v.color, v.stock FROM p"
                 " JOIN v IN p.variants WHERE v.stock < @low", low=5):
    print(row)
print("EXISTS:", query("SELECT VALUE p.name FROM p WHERE EXISTS("
                       "SELECT VALUE v FROM v IN p.variants"
                       " WHERE v.stock < @low)", low=5))
""")
run('python join.py')

# Step 6: COUNT, SUM, AVG and GROUP BY inside one partition (store-1)
write('agg.py', """\
from azure.cosmos import PartitionKey
from common import db

sales = db.create_container_if_not_exists(
    "sales", partition_key=PartitionKey(path="/storeId"))
rows = [("store-1", "games", 40.5), ("store-1", "books", 12.25),
        ("store-1", "games", 25.75), ("store-1", "toys", 8.5),
        ("store-1", "books", 18.5), ("store-1", "games", 30.25),
        ("store-1", "toys", 11.75), ("store-1", "books", 9.5),
        ("store-2", "games", 22.5), ("store-2", "toys", 15.25)]
for n, (store, category, amount) in enumerate(rows, start=1):
    sales.upsert_item({"id": f"sale-{n}", "storeId": store,
                       "category": category, "amount": amount})

totals = ("SELECT COUNT(1) AS sales, SUM(c.amount) AS total,"
          " AVG(c.amount) AS average FROM c")
print(list(sales.query_items(totals, partition_key="store-1")))
by_category = ("SELECT c.category, COUNT(1) AS sales,"
               " SUM(c.amount) AS total FROM c GROUP BY c.category")
for row in sales.query_items(by_category, partition_key="store-1"):
    print(row)
""")
run('python agg.py')

# Step 7: Paging with max_item_count and a continuation token
write('page.py', """\
from common import db

sales = db.get_container_client("sales")
sql = "SELECT c.id, c.amount FROM c"
pages = sales.query_items(sql, partition_key="store-1",
                          max_item_count=3).by_page()
first = list(next(pages))
token = pages.continuation_token            # a bookmark: save it
print("page 1:", len(first), "items | token is not None:",
      token is not None)

rest = sales.query_items(sql, partition_key="store-1",
                         max_item_count=3).by_page(token)  # resume
for n, page in enumerate(rest, start=2):
    print(f"page {n}:", len(list(page)), "items | token is not None:",
          rest.continuation_token is not None)
""")
run('python page.py')

# Step 8: The improved product search: partition key, ARRAY_CONTAINS, projection, TOP and a composite index
write('search.py', """\
import json
from common import products

ORDER = [{"path": "/rating", "order": "descending"},
         {"path": "/price", "order": "ascending"}]
catalog = products("catalog", indexing_policy={
    "includedPaths": [{"path": "/*"}],
    "excludedPaths": [{"path": "/description/*"}],
    "compositeIndexes": [ORDER]})
for item in json.load(open("products.json")):
    catalog.upsert_item(item)

sql = ("SELECT TOP @n c.id, c.name, c.price, c.rating FROM c"
       " WHERE c.category = @cat AND ARRAY_CONTAINS(c.tags, @tag)"
       " ORDER BY c.rating DESC, c.price ASC")
params = [{"name": "@n", "value": 10},
          {"name": "@cat", "value": "games"},
          {"name": "@tag", "value": "family"}]
for row in catalog.query_items(sql, parameters=params,
                               partition_key="games"):
    print(row)
""")
run('python search.py')
Next in this series

Part 6: Consistency and Global Distribution

The sample data on this page is invented for teaching. Every terminal output is the real output of the command above it, run on the official Azure Cosmos DB Linux emulator (vNext) with azure-cosmos 4.17.1. Features the emulator does not support are shown as code. Part of the Real Time Azure Cosmos DB Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of October 2026; check the official Azure Cosmos DB documentation (learn.microsoft.com/azure/cosmos-db) for anything you quote in an interview.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.