Introduction This article explains how to create documents in SQL (DocumentDB) API. Before starting, we need to understand what is documentDb and how it works. SQL (DocumentDB) API is one of the APIs that comes under Azure COSMOS DB.
Azure Cosmos DbThis is one of the most important parts of Microsoft Azure. Azure Cosmos Db has a globally distributed database. It has lots of features available like global distribution, which means turnkey distribution in more than 30 regions, you can scale it horizontally (scale storage and throughput), low latency, which means it gives high performance (99.999% read in < 10ms and 99.99% write in <15ms), also it is highly available.
Cosmos Db has the following multi-model APIs,
- SQL API(DocumentDB)
- MongoDB API
- Gremlin API(GraphDB)
- Table API
- Cassandra API
So, let’s start with DocumentDB
Azure Cosmos Db SQL API has all the features as mentioned above.
- Create Azure Cosmos DB database
Click Create a resource > Databases > Azure Cosmos DB.
- Create a Cosmos DB account.
- Enter the Account ID
- API as SQL API
- Subscription whatever you have
- Resource Group.
- Location etc
- Now, we will create a collection. Collections are like containers in which we can create documents, and documents are JSON objects.
Enter the Database Id, Collection Id and throughput as shown in the below screenshot.
We created resources manually over the Azure portal, you can also create them by coding. Let’s start the coding for creating documents into the ToDoList Collection.
- Create a console application. I have created it in the dot net core 2.0.
5. Install NuGet for SQL API into DocumentDbDemo project. So we can connect with the Azure document DB.
6. Get the connection string of cosmos DB (we have created earlier ) from the Azure portal.
7. Create a appsetting.json file. I have created an environment specific file for the development environment. So we can check in the program file, and we will see in the code.
8. We will create a Config.cs class that will contain the properties to get the values of the appsettings.dev.json file.
- public class Config
- {
- public DocDbConnectionString docDb { get; set; }
- }
- public class DocDbConnectionString
- {
- public string EndPoint { get; set; }
- public string AuthKey { get; set; }
- public string Database { get; set; }
- public string Collection { get; set; }
- }
- Let’s come to program.cs file and do the basic configuration code.
First, set the environment variable -- right click on DocumentDbDemo>Debug>Add>ASPNETCORE_ENVIRONMENT=dev. So you will get the dev environment file in program.cs.- class Program
- {
- private static IConfiguration Configuration { get; set; }
- private static Config configs;
- private DocumentClient client;
- static void Main(string[] args)
- {
- // Setup Configuration
- var builder = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: false, reloadOnChange: true);
- Configuration = builder.Build();
- configs = new Config();
- Configuration.Bind(configs);
- Program obj = new Program();
- obj.CRUDOperation().Wait();
- }
- //Get a single instance of Document client and reuse
- public DocumentClient Client
- {
- get
- {
- if (client == null)
- {
- Uri endpointUri = new Uri(configs.docDb.EndPoint);
- client = new DocumentClient(endpointUri, configs.docDb.AuthKey, null, ConsistencyLevel.Session);
- client.OpenAsync();
- }
- return client;
- }
- }
- }
- var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);
- // create jobject which contain the employee details
- Console.WriteLine("\nCreating document");
- JObject emp = new JObject();
- emp.Add("id", "V001");
- emp.Add("name", "virendra");
- emp.Add("address", "Indore");
- emp.Add("Country", "India");
- // create the document
- var createResponse = await Client.CreateDocumentAsync(collection, emp);
- var createdDocument = createResponse.Resource;
- Console.WriteLine("Document with id {0} created", createdDocument.Id);
11. Now , we can read that created document by Id
See the below as output,
- //Read document by Id
- eadResponse = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
- var readDocument = readResponse.Resource;
- Console.WriteLine("Read Document {0}: ",readResponse.Resource.ToString());
12. Now , we will go for updating the document by changing the value of address property.
See the below image of the updated document.
- // create jObject which contain the employee
- JObject updateEmp = new JObject();
- updateEmp.Add("id", "V001");
- updateEmp.Add("name", "virendra");
- updateEmp.Add("address", "pune");
- updateEmp.Add("Country", "India");
- Console.WriteLine("\nUpdating and Adding new property to document");
- //now update the document
- var updateResponse = await Client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"), updateEmp);
- var updated = updateResponse.Resource;
- Console.WriteLine("Document with id {0} Updated", updated.Id);
13. Now, we will finally delete that document from the collection.
See, deleted V001 document from the collection.
- // Delete the Document
- var deleteResponse = await Client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
- Console.WriteLine("Document Deleted");
- Below is the complete code of program.cs class.
- class Program
- {
- private static IConfiguration Configuration { get; set; }
- private static Config configs;
- private DocumentClient client;
- static void Main(string[] args)
- {
- // Setup Configuration
- var builder = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: false, reloadOnChange: true);
- Configuration = builder.Build();
- configs = new Config();
- Configuration.Bind(configs);
- Program obj = new Program();
- obj.CRUDOperation().Wait();
- }
- //CRUD Operation
- private async Task CRUDOperation()
- {
- var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);
- try
- {
- // create jobject which contain the employee details
- Console.WriteLine("\nCreating document");
- JObject emp = new JObject();
- emp.Add("id", "V001");
- emp.Add("name", "virendra");
- emp.Add("address", "Indore");
- emp.Add("Country", "India");
- // create the document
- var createResponse = await Client.CreateDocumentAsync(collection, emp);
- var createdDocument = createResponse.Resource;
- Console.WriteLine("Document with id {0} created", createdDocument.Id);
- }
- catch (DocumentClientException docEx)
- {
- if (docEx.StatusCode == HttpStatusCode.Conflict)
- {
- // create jObject which contain the employee
- JObject updateEmp = new JObject();
- updateEmp.Add("id", "V001");
- updateEmp.Add("name", "virendra");
- updateEmp.Add("address", "pune");
- updateEmp.Add("Country", "India");
- Console.WriteLine("\nUpdating and Adding new property to document");
- //now update the document
- var updateResponse = await Client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"), updateEmp);
- var updated = updateResponse.Resource;
- Console.WriteLine("Document with id {0} Updated", updated.Id);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- //Read document by Id
- var readResponse = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
- var readDocument = readResponse.Resource;
- Console.WriteLine("Read Document {0}: ",readResponse.Resource.ToString());
- // Delete the Document
- var deleteResponse = await Client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
- Console.WriteLine("Document Deleted");
- Console.ReadKey();
- }
- //Get a single instance of Document client and reuse
- public DocumentClient Client
- {
- get
- {
- if (client == null)
- {
- Uri endpointUri = new Uri(configs.docDb.EndPoint);
- client = new DocumentClient(endpointUri, configs.docDb.AuthKey, null, ConsistencyLevel.Session);
- client.OpenAsync();
- }
- return client;
- }
- }
- }
Thank you.
No comments:
Post a Comment