पाठ 15 / 25
Azure Cosmos DB
Model data around a partition key and choose a consistency level.
Globally distributed NoSQL
Azure Cosmos DB is a fully managed NoSQL database with single-digit-millisecond reads at any scale and optional multi-region writes. It offers several APIs: NoSQL (the native JSON document API, queried with a SQL-like language), MongoDB, Apache Cassandra, Apache Gremlin and Table. Throughput is measured in Request Units (RU/s), either provisioned (manual or autoscale) or serverless. Data is spread across physical partitions by a partition key you choose per container; a good key has many distinct values, spreads writes evenly and appears in most queries. Cosmos DB offers five consistency levels: Strong, Bounded staleness, Session (the default, which gives read-your-own-writes within a session), Consistent prefix and Eventual, trading latency and availability for stronger guarantees.
Querying within one partition
Including the partition key in a query keeps it to one partition, which is cheaper in RUs than a cross-partition query.
from azure.identity import DefaultAzureCredential
from azure.cosmos import CosmosClient
client = CosmosClient("https://cosmos-shop-dev.documents.azure.com", DefaultAzureCredential())
orders = client.get_database_client("shop").get_container_client("orders") # partition key: /customerId
orders.upsert_item({"id": "o-1001", "customerId": "c-42", "total": 1499})
items = orders.query_items(
query="SELECT * FROM o WHERE o.customerId = @c AND o.total > @min",
parameters=[{"name": "@c", "value": "c-42"}, {"name": "@min", "value": 1000}],
partition_key="c-42",
)
for order in items:
print(order["id"], order["total"])A bad partition key is expensive to fix
Partitioning by something like status or country creates a few huge, hot partitions. The partition key cannot be changed in place, so fixing it means copying data to a new container. Model the queries you need before creating containers.
त्वरित जाँच: Which consistency level is the Cosmos DB default and guarantees a client reads its own writes?
- Strong
- Eventual
- Session
- Consistent prefix
Answer
Session — Session consistency is the default and gives read-your-own-writes within a client session.