You are on page 1of 35

Module 04: Develop

solutions that use Azure


Cosmos DB

© Copyright Microsoft Corporation. All rights reserved.


Explore Azure Cosmos DB

Module
Agenda Implement partitioning in Azure Cosmos DB

Work with Azure Cosmos DB

© Copyright Microsoft Corporation. All rights reserved.


Lesson 1: Explore Azure Cosmos DB

© Copyright Microsoft Corporation. All rights reserved.


Introduction
After completing this module, you'll be able to:
• Identify the key benefits provided by Azure Cosmos DB.
• Describe the elements in an Azure Cosmos DB account and how they are organized.
• Explain the different consistency levels and choose the correct one for your project.
• Explore the APIs supported in Azure Cosmos DB and choose the appropriate API for
your solution.
• Describe how request units impact costs.
• Create Azure Cosmos DB resources by using the Azure portal.

© Copyright Microsoft Corporation. All rights reserved.


Identify key benefits of Azure Cosmos DB

Global replication: Automatic and synchronous multi-region replication, supports automatic and manual failover

Varied consistency levels: Offers five consistency models. Provides control over performance-consistency tradeoffs,
backed by comprehensive SLAs

Low latency: Serve <10 ms read and <10 ms write requests at the 99th percentile

Elastic scale-out: Elastically scale throughput from 10 to 100s of millions of requests/sec across multiple regions

© Copyright Microsoft Corporation. All rights reserved.


Explore the resource hierarchy (1 / 2)

Elements in an Azure Cosmos Azure Cosmos databases Azure Cosmos containers Azure Cosmos items
account
You can create one or multiple An Azure Cosmos container is Depending on which API you
An Azure Cosmos container is Azure Cosmos databases under the unit of scalability both for use, an Azure Cosmos item can
the fundamental unit of your account. A database is provisioned throughput and represent either a document in a
scalability. analogous to a namespace. storage. collection, a row in a table, or a
node or edge in a graph.
Azure Cosmos DB transparently A database is the unit of A container is horizontally
partitions your container using management for a set of Azure partitioned and then replicated
the logical partition key that you Cosmos containers. across multiple regions.
specify in order to elastically
scale your provisioned
throughput and storage.

© Copyright Microsoft Corporation. All rights reserved.


Explore the resource hierarchy (2 / 2)

© Copyright Microsoft Corporation. All rights reserved.


Explore consistency levels (1 / 2)

Azure Cosmos DB approaches data consistency as a spectrum of choices instead of two extremes.

© Copyright Microsoft Corporation. All rights reserved.


Explore consistency levels (2 /2)
Consistency Level Description
When a write operation is performed on your primary database, the write operation is replicated to the replica
Strong instances. The write operation is committed (and visible) on the primary only after it has been committed and
confirmed by all replicas.

This level is similar to the Strong level with the major difference that you can configure how stale documents can
Bounded Staleness be within replicas. Staleness refers to the quantity of time (or the version count) a replica document can be
behind the primary document.

This level guarantees that all read and write operations are consistent within a user session. Within the user
Session
session, all reads and writes are monotonic and guaranteed to be consistent across primary and replica instances.

This level has loose consistency but guarantees that when updates show up in replicas, they will show up in the
Consistent Prefix
correct order (that is, as prefixes of other updates) without any gaps.

This level has the loosest consistency and essentially commits any write operation against the primary
immediately. Replica transactions are asynchronously handled and will eventually (over time) be consistent with
Eventual
the primary. This tier has the best performance, because the primary database does not need to wait for replicas
to commit to finalize its transactions.

© Copyright Microsoft Corporation. All rights reserved.


Choose the right consistency level

Cassandra, MongoDB, and Consistency guarantees in


SQL API and Table API
Gremlin APIs practice

For many real-world scenarios, session Azure Cosmos DB provides native support for Consistency guarantees for a read operation
consistency is optimal and it's the wire protocol-compatible APIs for popular correspond to the freshness and ordering of
recommended option. databases. the database state that you request.

If your application requires strong


These include MongoDB, Apache Cassandra, Read-consistency is tied to the ordering and
consistency, it is recommended that you use
and Gremlin. propagation of the write/update operations.
bounded staleness consistency level.

If you need the highest availability and the When using Gremlin API the default This metric provides an insight into how often
lowest latency, then use eventual consistency consistency level configured on the Azure you can get a stronger consistency than the
level. Cosmos account is used. consistency level that you have currently
configured on your Azure Cosmos account.

© Copyright Microsoft Corporation. All rights reserved.


Explore supported APIs

Core(SQL) API: This API stores data in document format. It offers the best end-to-end experience as we have full
control over the interface, service, and the SDK client libraries.

API for MongoDB: This API stores data in a document structure, via BSON format. It is compatible with MongoDB
wire protocol.

Cassandra API: This API stores data in column-oriented schema and is wire protocol compatible with Apache
Cassandra.

Table API: This API stores data in key/value format.

Gremlin API: This API allows users to make graph queries and stores data as edges and vertices.

© Copyright Microsoft Corporation. All rights reserved.


Discover request units

© Copyright Microsoft Corporation. All rights reserved.


Exercise: Create Azure Cosmos DB resources by using the
Azure portal

Create an Azure Cosmos DB Add a database and a Add data to your database.
account. container.

© Copyright Microsoft Corporation. All rights reserved.


Summary and knowledge check

© Copyright Microsoft Corporation. All rights reserved.


Lesson 2: Implement partitioning in Azure
Cosmos DB

© Copyright Microsoft Corporation. All rights reserved.


Introduction
After completing this module, you'll be able to:
• Describe the differences between logical and physical partitions.
• Choose the appropriate partition key for your solution.
• Create a synthetic partition key.

© Copyright Microsoft Corporation. All rights reserved.


Explore partitions (1 / 2)

Logical partitions Physical partitions


A logical partition consists of a set of items that One or more logical partitions are mapped to a
have the same partition key. single physical partition.
A logical partition also defines the scope of Physical partitions are an internal implementation of
database transactions. the system and they are entirely managed by Azure
Cosmos DB.

© Copyright Microsoft Corporation. All rights reserved.


Explore partitions (2 / 2)

Partition Key: User ID

Azure Cosmos DB Container Logical Partitioning


(for example, Collection) Abstraction

Behind the scenes:


hash(User ID) Physical partition sets

Psuedo-random distribution of data over the range of possible hashed values


Dharma


Andrew Shireesh
Karthik
Mike Bob Rimma


Alice


Carol

Partition 1 Partition 2 Partition n

Frugal number of partitions based on actual storage and throughput needs

© Copyright Microsoft Corporation. All rights reserved.


Choose a partition key

Partition keys for read-heavy containers Using item ID as the partition key
For large read-heavy containers you might want to If your container has a property that has a wide
choose a partition key that appears frequently as a range of possible values, it is likely a great partition
filter in your queries. key choice.
Queries can be efficiently routed to only the relevant For small read-heavy containers or write-heavy
physical partitions by including the partition key in containers of any size, the item ID is naturally a
the filter predicate. great choice for the partition key.

© Copyright Microsoft Corporation. All rights reserved.


Create a synthetic partition key

Concatenate multiple properties of an item.

Use a partition key with a random suffix.

Use a partition key with pre-calculated suffixes.

© Copyright Microsoft Corporation. All rights reserved.


Summary and knowledge check

© Copyright Microsoft Corporation. All rights reserved.


Lesson 3: Work with Azure Cosmos DB

© Copyright Microsoft Corporation. All rights reserved.


Introduction
After completing this module, you'll be able to:
• Identify classes and methods used to create resources.
• Create resources by using the Azure Cosmos DB .NET v3 SDK.
• Write stored procedures, triggers, and user-defined functions by using JavaScript.

© Copyright Microsoft Corporation. All rights reserved.


Explore Microsoft .NET SDK v3 for Azure Cosmos DB (1 / 3)
Creating items
// Get container reference
CosmosClient client = new CosmosClient(endpoint, key);
Container container = client.GetContainer(databaseName, collectionName);

// create anonymous type in .NET


Product orangeSoda = new Product {
id = "7cc3212d-0e2c-4a13-b348-f2d879c43342",
name = "Orange Soda", group = "Beverages",
diet = false, price = 1.50m, quantity = 2000
};

// Upload item
Product item = await container.CreateItemAsync(orangeSoda);
Product item = await container.UpsertItemAsync(orangeSoda);

© Copyright Microsoft Corporation. All rights reserved.


Explore Microsoft .NET SDK v3 for Azure Cosmos DB (2 / 3)
Reading items
// Get container reference
CosmosClient client = new CosmosClient(endpoint, key);
Container container = client.GetContainer(databaseName, collectionName);

// Get unique fields


string id = "7cc3212d-0e2c-4a13-b348-f2d879c43342";
PartitionKey partitionKey = new PartitionKey("Beverages");

// Read item using unique id


ItemResponse<Product> response = await container.ReadItemAsync<Product>(
id,
partitionKey );

// Serialize response
Product item = response.Resource;

© Copyright Microsoft Corporation. All rights reserved.


Explore Microsoft .NET SDK v3 for Azure Cosmos DB (3 / 3)
Query documents
// Get container reference
CosmosClient client = new CosmosClient(endpoint, key);
Container container = client.GetContainer(databaseName, collectionName);

// Use SQL query language


FeedIterator<Product> iterator = container.GetItemQueryIterator<Product>(
"SELECT * FROM products p WHERE p.diet = false"
);

// Iterate over results


while (iterator.HasMoreResults)
{
FeedResponse<Product> batch = await iterator.ReadNextAsync();
foreach(Product item in batch) { }
}

© Copyright Microsoft Corporation. All rights reserved.


Exercise : Create resources by using the Microsoft .NET SDK v3

Prepare your environment Build the console app Create a database

Create a container Run the application Clean up Azure resources

© Copyright Microsoft Corporation. All rights reserved.


Create stored procedures (1 / 4)

In Azure Cosmos DB, JavaScript is hosted in the same memory space as the database

Requests made within stored procedures and triggers run in the same scope of a database session

© Copyright Microsoft Corporation. All rights reserved.


Create stored procedures (2 / 4)
Example code
function createSampleDocument(documentToCreate) {
var context = getContext();
var collection = context.getCollection();
var accepted = collection.createDocument(
collection.getSelfLink(),
documentToCreate,
function (error, documentCreated) {
context.getResponse().setBody(documentCreated.id)
}
);
if (!accepted) return;
}

© Copyright Microsoft Corporation. All rights reserved.


Create stored procedures (3 / 4)
Bounded execution

All Azure Cosmos DB operations must complete within a limited amount


of time

© Copyright Microsoft Corporation. All rights reserved.


Create stored procedures (4 / 4)
Transaction continuation
JavaScript functions can implement a continuation-based model to batch or resume
execution
• The continuation value can be any value of your choice
• Your applications can then use this value to resume a transaction from a new starting
point
Bulk create documents

Return a pointer to resume


later

© Copyright Microsoft Corporation. All rights reserved.


Create triggers and user-defined functions

Pre-triggers: Executed before modifying, or creating, a database item.

Post-triggers: Executed after modifying a database item

User-defined function: User-defined functions extend the Azure Cosmos DB SQL API’s query language grammar and
implement custom business logic.

© Copyright Microsoft Corporation. All rights reserved.


Summary and knowledge check

© Copyright Microsoft Corporation. All rights reserved.


Lab 04: Constructing a
Lab 04: Constructing
polyglot data solution
a polyglot data
solution
http://aka.ms/az204labs
45
minutes

http://aka.ms/az204labs

© Copyright Microsoft Corporation. All rights reserved.


© Copyright Microsoft Corporation. All rights reserved.

You might also like