Concepts

Microsoft Azure Cosmos DB is a globally distributed database service that provides high availability and scalability with comprehensive SLAs. It supports multiple data models, including document, key-value, column-family, graph, and time-series data. In this article, we will focus on the document data model and explore how to implement a point operation that creates, updates, and deletes documents related to an exam.

Prerequisites

Before we dive into the implementation details, make sure you have the following prerequisites in place:

  1. An Azure subscription: You will need an Azure subscription to create and manage resources in Azure.
  2. Azure Cosmos DB account: Create an Azure Cosmos DB account in the Azure portal. Select the “SQL API” option when creating the account as we will be using the SQL API to interact with the data.
  3. Programming environment: Choose a programming language and framework of your choice that supports Azure Cosmos DB. This article assumes you will be using C# and the .NET framework.

Creating the Document Database

To begin, let’s create a document database to store our exam-related data. Follow the steps below:

  1. Navigate to the Azure portal (portal.azure.com) and sign in with your Azure account.
  2. Click on “Create a Resource” and search for “Azure Cosmos DB”.
  3. Click on “Azure Cosmos DB” and then click “Create”.
  4. Provide a unique ID for your Azure Cosmos DB account, select the desired API (SQL API), and choose the appropriate subscription and resource group.
  5. Specify the geographic location where you want your data to be stored.
  6. Under the “Settings” tab, select “Enable multi-region writes” if you want to enable writes from multiple regions.
  7. Click “Review + Create” and then click “Create” to create the Azure Cosmos DB account.

Once the Cosmos DB account is created, we can proceed with implementing the point operations for creating, updating, and deleting exam-related documents.

Creating a Document

To create a document in Azure Cosmos DB, we need to establish a connection and use the appropriate client SDK. In this example, we will be using the .NET SDK. Here’s a sample code snippet to create an exam document:

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Newtonsoft.Json;
using System;

public class Exam
{
[JsonProperty("id")]
public string Id { get; set; }

[JsonProperty("subject")]
public string Subject { get; set; }

[JsonProperty("duration")]
public int Duration { get; set; }
}

public class CosmosDBHelper
{
private static readonly string EndpointUrl = "";
private static readonly string PrimaryKey = "";
private static readonly string DatabaseId = "Exams";
private static readonly string CollectionId = "ExamCollection";

private static DocumentClient client;

public static async Task CreateExamAsync(Exam exam)
{
using (client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey))
{
await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), exam);
}
}
}

public class Program
{
public static void Main(string[] args)
{
Exam exam = new Exam
{
Id = Guid.NewGuid().ToString(),
Subject = "Math",
Duration = 120
};

CosmosDBHelper.CreateExamAsync(exam).GetAwaiter().GetResult();
}
}

In the above code snippet, we define a CosmosDBHelper class that handles the document creation. We create an instance of the DocumentClient class using the Cosmos DB account endpoint URL and primary key. In the CreateExamAsync method, we use the document client to create a document by passing the database and collection URIs along with the exam object.

Updating a Document

To update a document in Azure Cosmos DB, we need to retrieve the document, make the necessary changes, and then replace the document in the database. Here’s a sample code snippet to update an exam document:

public class CosmosDBHelper
{
// ...

public static async Task UpdateExamAsync(Exam exam)
{
using (client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey))
{
// Retrieve the document
Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, exam.Id));

// Update the document
document.SetPropertyValue("duration", exam.Duration);
document.SetPropertyValue("subject", exam.Subject);

// Replace the document
await client.ReplaceDocumentAsync(document.SelfLink, document);

}
}
}

public class Program
{
public static void Main(string[] args)
{
Exam exam = new Exam
{
Id = "",
Subject = "Physics",
Duration = 180
};

CosmosDBHelper.UpdateExamAsync(exam).GetAwaiter().GetResult();
}
}

In the above code snippet, the UpdateExamAsync method retrieves the existing document by its ID. We then update the desired properties of the document and replace it in the database using the ReplaceDocumentAsync method.

Deleting a Document

Deleting a document is straightforward. We only need to provide the document ID and the document’s self-link to delete it from the database. Here’s a sample code snippet to delete an exam document:

public class CosmosDBHelper
{
// ...

public static async Task DeleteExamAsync(string examId)
{
using (client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey))
{
// Retrieve the document self-link
Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, examId));

// Delete the document
await client.DeleteDocumentAsync(document.SelfLink);
}
}
}

public class Program
{
public static void Main(string[] args)
{
string examId = "";

CosmosDBHelper.DeleteExamAsync(examId).GetAwaiter().GetResult();
}
}

In the above code snippet, the DeleteExamAsync method retrieves the existing document by its ID and then deletes it using the DeleteDocumentAsync method.

Conclusion

In this article, we explored how to implement point operations that create, update, and delete exam-related documents using Microsoft Azure Cosmos DB. We leveraged the .NET SDK to interact with the database and demonstrated sample code for each operation. Azure Cosmos DB provides an excellent platform for building scalable, globally distributed applications, and the document data model makes it easy to work with complex data structures.

Remember to explore the Azure Cosmos DB documentation for more in-depth information and to adapt the code samples to fit your specific requirements. Happy coding!

Answer the Questions in Comment Section

Which operation is used to create new documents in Azure Cosmos DB?

  • a) PUT
  • b) POST
  • c) PATCH
  • d) DELETE

Correct answer: b) POST

In Azure Cosmos DB, what is the maximum size of a document that can be created?

  • a) 1 MB
  • b) 2 MB
  • c) 4 MB
  • d) 8 MB

Correct answer: c) 4 MB

Which HTTP status code is returned when a document is successfully created in Azure Cosmos DB?

  • a) 200 OK
  • b) 201 Created
  • c) 204 No Content
  • d) 400 Bad Request

Correct answer: b) 201 Created

What is the maximum number of databases that can be created in an Azure Cosmos DB account?

  • a) 5
  • b) 10
  • c) 25
  • d) Unlimited

Correct answer: d) Unlimited

Which API must be used to create and manage documents in Azure Cosmos DB?

  • a) SQL API
  • b) MongoDB API
  • c) Table API
  • d) Cassandra API

Correct answer: a) SQL API

In Azure Cosmos DB, which property is used as the unique identifier for a document?

  • a) _id
  • b) _self
  • c) _etag
  • d) _rid

Correct answer: a) _id

What happens when a document is updated in Azure Cosmos DB?

  • a) The old document is deleted and a new document is created.
  • b) The document is replaced with the updated version.
  • c) A new version of the document is created with the updates.
  • d) The update operation fails and an error is returned.

Correct answer: b) The document is replaced with the updated version.

Which HTTP status code is returned when a document is successfully updated in Azure Cosmos DB?

  • a) 200 OK
  • b) 201 Created
  • c) 204 No Content
  • d) 400 Bad Request

Correct answer: c) 204 No Content

In Azure Cosmos DB, which operation is used to delete a document?

  • a) DELETE
  • b) REMOVE
  • c) DROP
  • d) ERASE

Correct answer: a) DELETE

Which property should be used to specify the partition key value when deleting a document in Azure Cosmos DB?

  • a) _id
  • b) _self
  • c) _etag
  • d) _partitionKey

Correct answer: d) _partitionKey

0 0 votes
Article Rating
Subscribe
Notify of
guest
21 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
ثنا کوتی
11 months ago

Great article on implementing point operations in Cosmos DB!

Ezra Edwards
1 year ago

Can someone explain the use of Azure Cosmos DB SDK for point operations?

Carl Carter
11 months ago

How can we ensure data consistency during point operations?

Frederikke Larsen
1 year ago

Thanks for this post, it simplified a lot for me!

Emma Chambers
11 months ago

Appreciate the detailed explanation on point operations.

Nander In 't Veld
1 year ago

I found the section on updating documents particularly useful. Thanks!

Lyubomil Luchanko
1 year ago

What should be the partition key strategy for efficient point operations?

Frederik Madsen
1 year ago

Thank you, this was very helpful!

21
0
Would love your thoughts, please comment.x
()
x