Azure Cosmos DB is a database solution provided from Microsoft Azure that provides 99.999% SLA for enterprise level solutions.
In this article I will demonstrate how you can write a simple .NET application to insert and fetch data from a Cosmos DB.
First things first, you should have already a cosmos DB created. Then you will need to navigate in the keys section on Azure and retrieve your connection keys.
Using data explorer on Azure you can easily create new Databases and Containers. Containers are like Tables, but they also include other entities like Stored Procedures Triggers and User Defined Functions.
In my test I created a new Database named Data on which I created the table Locations. In this location table I wanted to append some location entries, that they will contain Longitude and Latitude.
That is why I created a class inside my Console App named Location
public class Location { public Double Longtitude { get; set; } public Double Latitude { get; set; } [JsonProperty(PropertyName = "id")] public string Id { get; set; } }
My Program.cs is shown below:
Key points of the implementation:
- On the GetStartedDemoAsync the connection with the Cosmos DB is initialized using the connection strings and the database and container names. Its important to use the connectionMode Gateway because you will maybe face connection issues.
- The function AddItemsToContainerAsync is used to insert values on the database. A common issue happens with the PartitionKey that is mandatory to be used on the CreateItemAsync function. In my case I use a random Guid value for it. You should define a JsonProperty on your model with the PartitionKey value and provide a value along with your data. On my Location loc constructor I append a new Guid as the Id value.
- The QueryItemsAsync is used to retrieve the database values in a structure as your model.
The partition key is used to distribute your data into logical partition for scalability reasons. You should consider choosing an better value that is not random in order to take advantage of the Cosmos DB indexing engine.
Inside Task Main I used a while loop in order to insert some data on the cosmos DB database. As I do not have an external API source for the locations, the same location is added over and over again.
while(true)
{
await AddItemsToContainerAsync();
Thread.Sleep(5000);
}
Retrieving the values from the database.