DocumentDB – Create Collection ”; Previous Next In this chapter, we will learn how to create a collection. It is similar to creating a database. You can create a collection either from the portal or from the code using .Net SDK. Step 1 − Go to main dashboard on Azure portal. Step 2 − Select myfirstdb from the databases list. Step 3 − Click on the ‘Add Collection’ option and specify the ID for collection. Select the Pricing Tier for different option. Step 4 − Let’s select S1 Standard and click Select → OK button. As you can see that MyCollection is added to the myfirstdb. You can also create collection from the code by using .Net SDK. Let’s have a look at the following steps to add collections from the code. Step 1 − Open the Console application in Visual Studio. Step 2 − To create a collection, first retrieve the myfirstdb database by its ID in the CreateDocumentClient task. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”myfirstdb””).AsEnumerable().First(); await CreateCollection(client, “MyCollection1”); await CreateCollection(client, “MyCollection2”, “S2”); } } Following is the implementation for CreateCollection task. private async static Task CreateCollection(DocumentClient client, string collectionId, string offerType = “S1”) { Console.WriteLine(); Console.WriteLine(“**** Create Collection {0} in {1} ****”, collectionId, database.Id); var collectionDefinition = new DocumentCollection { Id = collectionId }; var options = new RequestOptions { OfferType = offerType }; var result = await client.CreateDocumentCollectionAsync(database.SelfLink, collectionDefinition, options); var collection = result.Resource; Console.WriteLine(“Created new collection”); ViewCollection(collection); } We create a new DocumentCollection object that defines the new collection with the desired Id for the CreateDocumentCollectionAsync method which also accepts an options parameter that we”re using here to set the performance tier of the new collection, which we”re calling offerType. This defaults to S1 and since we didn”t pass in an offerType, for MyCollection1, so this will be an S1 collection and for MyCollection2 we have passed S2 which make this one an S2 as shown above. Following is the implementation of the ViewCollection method. private static void ViewCollection(DocumentCollection collection) { Console.WriteLine(“Collection ID: {0} “, collection.Id); Console.WriteLine(“Resource ID: {0} “, collection.ResourceId); Console.WriteLine(“Self Link: {0} “, collection.SelfLink); Console.WriteLine(“Documents Link: {0} “, collection.DocumentsLink); Console.WriteLine(“UDFs Link: {0} “, collection.UserDefinedFunctionsLink); Console.WriteLine(” StoredProcs Link: {0} “, collection.StoredProceduresLink); Console.WriteLine(“Triggers Link: {0} “, collection.TriggersLink); Console.WriteLine(“Timestamp: {0} “, collection.Timestamp); } Following is the complete implementation of program.cs file for collections. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Newtonsoft.Json; namespace DocumentDBDemo { class Program { private const string EndpointUrl = “https://azuredocdbdemo.documents.azure.com:443/”; private const string AuthorizationKey = “BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/ StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==”; private static Database database; static void Main(string[] args) { try { CreateDocumentClient().Wait(); } catch (Exception e) { Exception baseException = e.GetBaseException(); Console.WriteLine(“Error: {0}, Message: {1}”, e.Message, baseException.Message); } Console.ReadKey(); } private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”myfirstdb””).AsEnumerable().First(); await CreateCollection(client, “MyCollection1”); await CreateCollection(client, “MyCollection2”, “S2”); //await CreateDatabase(client); //GetDatabases(client); //await DeleteDatabase(client); //GetDatabases(client); } } private async static Task CreateCollection(DocumentClient client, string collectionId, string offerType = “S1”) { Console.WriteLine(); Console.WriteLine(“**** Create Collection {0} in {1} ****”, collectionId, database.Id); var collectionDefinition = new DocumentCollection { Id = collectionId }; var options = new RequestOptions { OfferType = offerType }; var result = await client.CreateDocumentCollectionAsync(database.SelfLink, collectionDefinition, options); var collection = result.Resource; Console.WriteLine(“Created new collection”); ViewCollection(collection); } private static void ViewCollection(DocumentCollection collection) { Console.WriteLine(“Collection ID: {0} “, collection.Id); Console.WriteLine(“Resource ID: {0} “, collection.ResourceId); Console.WriteLine(“Self Link: {0} “, collection.SelfLink); Console.WriteLine(“Documents Link: {0} “, collection.DocumentsLink); Console.WriteLine(“UDFs Link: {0} “, collection.UserDefinedFunctionsLink); Console.WriteLine(“StoredProcs Link: {0} “, collection.StoredProceduresLink); Console.WriteLine(“Triggers Link: {0} “, collection.TriggersLink); Console.WriteLine(“Timestamp: {0} “, collection.Timestamp); } } } When the above code is compiled and executed, you will receive the following output which contains all the information related to collection. **** Create Collection MyCollection1 in myfirstdb **** Created new collection Collection ID: MyCollection1 Resource ID: Ic8LAPPvnAA= Self Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/ Documents Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/docs/ UDFs Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/udfs/ StoredProcs Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/sprocs/ Triggers Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/triggers/ Timestamp: 12/10/2015 4:55:36 PM **** Create Collection MyCollection2 in myfirstdb **** Created new collection Collection ID: MyCollection2 Resource ID: Ic8LAKGHDwE= Self Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/ Documents Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/docs/ UDFs Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/udfs/ StoredProcs Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/sprocs/ Triggers Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/triggers/ Timestamp: 12/10/2015 4:55:38 PM Print Page Previous Next Advertisements ”;
Category: documentdb
DocumentDB – Data Modeling
DocumentDB – Data Modeling ”; Previous Next While schema-free databases, like DocumentDB, make it super easy to embrace changes to your data model, you should still spend some time thinking about your data. You have a lot of options. Naturally, you can just work JSON object graphs or even raw strings of JSON text, but you can also use dynamic objects that lets you bind to properties at runtime without defining a class at compile time. You can also work with real C# objects, or Entities as they are called, which might be your business domain classes. Relationships Let’s take a look at the document”s hierarchal structure. It has a few top-level properties like the required id, as well as lastName and isRegistered, but it also has nested properties. { “id”: “AndersenFamily”, “lastName”: “Andersen”, “parents”: [ { “firstName”: “Thomas”, “relationship”: “father” }, { “firstName”: “Mary Kay”, “relationship”: “mother” } ], “children”: [ { “firstName”: “Henriette Thaulow”, “gender”: “female”, “grade”: 5, “pets”: [ { “givenName”: “Fluffy”, “type”: “Rabbit” } ] } ], “location”: { “state”: “WA”, “county”: “King”, “city”: “Seattle”}, “isRegistered”: true } For instance, the parents property is supplied as a JSON array as denoted by the square brackets. We also have another array for children, even though there”s only one child in the array in this example. So this is how you model the equivalent of one-to-many relationships within a document. You simply use arrays where each element in the array could be a simple value or another complex object, even another array. So one family can have multiple parents and multiple children and if you look at the child objects, they have a pet’s property that is itself a nested array for a oneto-many relationship between children and pets. For the location property, we”re combining three related properties, the state, county, and city into an object. Embedding an object this way rather than embedding an array of objects is similar to having a one-to-one relationship between two rows in separate tables in a relational database. Embedding Data When you start modeling data in a document store, such as DocumentDB, try to treat your entities as self-contained documents represented in JSON. When working with relational databases, we always normalize data. Normalizing your data typically involves taking an entity, such as a customer, and breaking it down into discreet pieces of data, like contact details and addresses. To read a customer, with all their contact details and addresses, you need to use JOINS to effectively aggregate your data at run time. Now let”s take a look at how we would model the same data as a self-contained entity in a document database. { “id”: “1”, “firstName”: “Mark”, “lastName”: “Upston”, “addresses”: [ { “line1”: “232 Main Street”, “line2”: “Unit 1”, “city”: “Brooklyn”, “state”: “NY”, “zip”: 11229 } ], “contactDetails”: [ {“email”: “[email protected]”}, {“phone”: “+1 356 545-86455”, “extension”: 5555} ] } As you can see that we have denormalized the customer record where all the information of the customer is embedded into a single JSON document. In NoSQL we have a free schema, so you can add contact details and addresses in different format as well. In NoSQL, you can retrieve a customer record from the database in a single read operation. Similarly, updating a record is also a single write operation. Following are the steps to create documents using .Net SDK. Step 1 − Instantiate DocumentClient. Then we will query for the myfirstdb database and also query for MyCollection collection, which we store in this private variable collection so that”s it”s accessible throughout the class. private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery(“SELECT * FROM c WHERE c.id = ”myfirstdb””).AsEnumerable().First(); collection = client.CreateDocumentCollectionQuery(database.CollectionsLink, “SELECT * FROM c WHERE c.id = ”MyCollection””).AsEnumerable().First(); await CreateDocuments(client); } } Step 2 − Create some documents in CreateDocuments task. private async static Task CreateDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“**** Create Documents ****”); Console.WriteLine(); dynamic document1Definition = new { name = “New Customer 1”, address = new { addressType = “Main Office”, addressLine1 = “123 Main Street”, location = new { city = “Brooklyn”, stateProvinceName = “New York” }, postalCode = “11229”, countryRegionName = “United States” }, }; Document document1 = await CreateDocument(client, document1Definition); Console.WriteLine(“Created document {0} from dynamic object”, document1.Id); Console.WriteLine(); } The first document will be generated from this dynamic object. This might look like JSON, but of course it isn”t. This is C# code and we”re creating a real .NET object, but there”s no class definition. Instead the properties are inferred from the way the object is initialized. You can notice also that we haven”t supplied an Id property for this document. Step 3 − Now let”s take a look at the CreateDocument and it looks like the same pattern we saw for creating databases and collections. private async static Task<Document> CreateDocument(DocumentClient client, object documentObject) { var result = await client.CreateDocumentAsync(collection.SelfLink, documentObject); var document = result.Resource; Console.WriteLine(“Created new document: {0}rn{1}”, document.Id, document); return result; } Step 4 − This time we call CreateDocumentAsync specifying the SelfLink of the collection we want to add the document to. We get back a response with a resource property that, in this case, represents the new document with its system-generated properties. In the following CreateDocuments task, we have created three documents. In the first document, the Document object is a defined class in the SDK that inherits from resource and so it has all the common resource properties, but it also includes the dynamic properties that define the schema-free document itself. private async static Task CreateDocuments(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“**** Create Documents ****”); Console.WriteLine(); dynamic document1Definition = new { name = “New Customer 1”, address = new { addressType = “Main Office”, addressLine1 = “123 Main Street”, location = new { city = “Brooklyn”, stateProvinceName = “New York” }, postalCode = “11229”, countryRegionName = “United States” }, }; Document document1 = await CreateDocument(client, document1Definition); Console.WriteLine(“Created document {0}
DocumentDB – List Databases
DocumentDB – List Databases ”; Previous Next So far, we have created two databases in our DocumentDB account, first one is created using Azure portal while the second database is created using .Net SDK. Now to view these databases, you can use Azure portal. Go to your DocumentDB account on Azure portal and you will see two databases now. You can also view or list the databases from your code using .Net SDK. Following are the steps involved. Step 1 − Issue a database Query with no parameters which returns a complete list, but you can also pass in a query to look for a specific database or specific databases. private static void GetDatabases(DocumentClient client) { Console.WriteLine(); Console.WriteLine(); Console.WriteLine(“******** Get Databases List ********”); var databases = client.CreateDatabaseQuery().ToList(); foreach (var database in databases) { Console.WriteLine(” Database Id: {0}; Rid: {1}”, database.Id, database.ResourceId); } Console.WriteLine(); Console.WriteLine(“Total databases: {0}”, databases.Count); } You will see that there are a bunch of these CreateQuery methods for locating collections, documents, users, and other resources. These methods don”t actually execute the query, they just define the query and return an iterateable object. It”s the call to ToList() that actually executes the query, iterates the results, and returns them in a list. Step 2 − Call GetDatabases method from the CreateDocumentClient task after DocumentClient is instantiated. Step 3 − You also need to comment the CreateDatabase task or change the database id, otherwise you will get an error message that the database exists. using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { //await CreateDatabase(client); GetDatabases(client); } Following is the complete Program.cs file so far. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Newtonsoft.Json; namespace DocumentDBDemo { class Program { private const string EndpointUrl = “https://azuredocdbdemo.documents.azure.com:443/”; private const string AuthorizationKey = “BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/ StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==”; static void Main(string[] args) { try { CreateDocumentClient().Wait(); } catch (Exception e) { Exception baseException = e.GetBaseException(); Console.WriteLine(“Error: {0}, Message: {1}”, e.Message, baseException.Message); } Console.ReadKey(); } private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { await CreateDatabase(client); GetDatabases(client); } } private async static Task CreateDatabase(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“******** Create Database *******”); var databaseDefinition = new Database { Id = “mynewdb” }; var result = await client.CreateDatabaseAsync(databaseDefinition); var database = result.Resource; Console.WriteLine(” Database Id: {0}; Rid: {1}”, database.Id, database.ResourceId); Console.WriteLine(“******** Database Created *******”); } private static void GetDatabases(DocumentClient client) { Console.WriteLine(); Console.WriteLine(); Console.WriteLine(“******** Get Databases List ********”); var databases = client.CreateDatabaseQuery().ToList(); foreach (var database in databases) { Console.WriteLine(” Database Id: {0}; Rid: {1}”, database.Id, database.ResourceId); } Console.WriteLine(); Console.WriteLine(“Total databases: {0}”, databases.Count); } } } When the above code is compiled and executed you will receive the following output which contains the Database and Resources IDs of both the databases. In the end you will also see the total number of databases. ******** Get Databases List ******** Database Id: myfirstdb; Rid: Ic8LAA== Database Id: mynewdb; Rid: ltpJAA== Total databases: 2 Print Page Previous Next Advertisements ”;
DocumentDB – Home
DocumentDB Tutorial PDF Version Quick Guide Resources Job Search Discussion DocumentDB is Microsoft”s newest NoSQL document database platform that runs on Azure. DocumentDB is designed keeping in mind the requirements of managing data for latest applications. This tutorial explains the basics of DocumentDB with illustrative examples. Audience This tutorial is designed for beginners, i.e., for developers who want to get acquainted with how DocumentDB works. Prerequisites It is an elementary tutorial that explains the basics of DocumentDB and there are no prerequisites as such. However, it will certainly help if you have some prior exposure to NoSQL technologies. Print Page Previous Next Advertisements ”;
DocumentDB – Introduction
DocumentDB – Introduction ”; Previous Next In this chapter, we will briefly discuss the major concepts around NoSQL and document databases. We will also have a quick overview of DocumentDB. NoSQL Document Database DocumentDB is Microsoft”s newest NoSQL document database, so when you say NoSQL document database then, what precisely do we mean by NoSQL, and document database? SQL means Structured Query Language which is traditional query language of relational databases. SQL is often equated with relational databases. It”s really more helpful to think of a NoSQL database as a non-relational database, so NoSQL really means non-relational. There are different types of NoSQL databases which include key value stores such as − Azure Table Storage. Column-based stores like Cassandra. Graph databases like NEO4. Document databases like MongoDB and Azure DocumentDB. Azure DocumentDB Microsoft officially launched Azure DocumentDB on April 8th, 2015, and it certainly can be characterized as a typical NoSQL document database. It”s massively scalable, and it works with schema-free JSON documents. DocumentDB is a true schema-free NoSQL document database service designed for modern mobile and web applications. It also delivers consistently fast reads and writes, schema flexibility, and the ability to easily scale a database up and down on demand. It does not assume or require any schema for the JSON documents it indexes. DocumentDB automatically indexes every property in a document as soon as the document is added to the database. DocumentDB enables complex ad-hoc queries using a SQL language, and every document is instantly queryable the moment it”s created, and you can search on any property anywhere within the document hierarchy. DocumentDB – Pricing DocumentDB is billed based on the number of collections contained in a database account. Each account can have one or more databases and each database can have a virtually unlimited number of collections, although there is an initial default quota of 100. This quota can be lifted by contacting Azure support. A collection is not only a unit of scale, but also a unit of cost, so in DocumentDB you pay per collection, which has a storage capacity of up to 10 GB. At a minimum, you”ll need one S1 collection to store documents in a database that will cost roughly $25 per month, which gets billed against your Azure subscription. As your database grows in size and exceeds 10 GB, you”ll need to purchase another collection to contain the additional data. Each S1 collection will give you 250 request units per second, and if that”s not enough, then you can scale the collection up to an S2 and get a 1000 request units per second for about $50 a month. You can also turn it all the way up to an S3 and pay around $100 a month. Print Page Previous Next Advertisements ”;
DocumentDB – Advantages
DocumentDB – Advantages ”; Previous Next DocumentDB stands out with some very unique capabilities. Azure DocumentDB offers the following key capabilities and benefits. Schema Free In a relational database, every table has a schema that defines the columns and data types that each row in the table must conform to. In contrast, a document database has no defined schema, and every document can be structured differently. SQL Syntax DocumentDB enables complex ad-hoc queries using SQL language, and every document is instantly queryable the moment it”s created. You can search on any property anywhere within the document hierarchy. Tunable Consistency It provides some granular, well-defined consistency levels, which allows you to make sound trade-offs between consistency, availability, and latency. You can select from four well-defined consistency levels to achieve optimal trade-off between consistency and performance. For queries and read operations, DocumentDB offers four distinct consistency levels − Strong Bounded-staleness Session Eventual Elastic Scale Scalability is the name of the game with NoSQL, and DocumentDB delivers. DocumentDB has already been proven its scale. Major services like Office OneNote and Xbox are already backed by DocumentDB with databases containing tens of terabytes of JSON documents, over a million active users, and operating consistently with 99.95% availability. You can elastically scale DocumentDB with predictable performance by creating more units as your application grows. Fully Managed DocumentDB is available as a fully managed cloud-based platform as a service running on Azure. There is simply nothing for you to install or manage. There are no servers, cables, no operating systems or updates to deal with, no replicas to set up. Microsoft does all that work and keeps the service running. Within literally minutes, you can get started working with DocumentDB using just a browser and an Azure subscription. Print Page Previous Next Advertisements ”;
DocumentDB – Create Database
DocumentDB – Create Database ”; Previous Next In this chapter, we will learn how to create a database. To use Microsoft Azure DocumentDB, you must have a DocumentDB account, a database, a collection, and documents. We already have a DocumentDB account, now to create database we have two options − Microsoft Azure Portal or .Net SDK Create a Database for DocumentDB using the Microsoft Azure Portal To create a database using portal, following are the steps. Step 1 − Login to Azure portal and you will see the dashboard. Step 2 − Now click on the created DocumentDB account and you will see the details as shown in the following screenshot. Step 3 − Select the Add Database option and provide the ID for your database. Step 4 − Click OK. You can see that the database is added. At the moment, it has no collection, but we can add collections later which are the containers that will store our JSON documents. Notice that it has both an ID and a Resource ID. Create a Database for DocumentDB Using .Net SDK To create a database using .Net SDK, following are the steps. Step 1 − Open the Console Application in Visual Studio from the last chapter. Step 2 − Create the new database by creating a new database object. To create a new database, we only need to assign the Id property, which we are setting to “mynewdb” in a CreateDatabase task. private async static Task CreateDatabase(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“******** Create Database *******”); var databaseDefinition = new Database { Id = “mynewdb” }; var result = await client.CreateDatabaseAsync(databaseDefinition); var database = result.Resource; Console.WriteLine(” Database Id: {0}; Rid: {1}”, database.Id, database.ResourceId); Console.WriteLine(“******** Database Created *******”); } Step 3 − Now pass this databaseDefinition on to CreateDatabaseAsync, and get back a result with a Resource property. All the create object methods return a Resource property that describes the item that was created, which is a database in this case. We get the new database object from the Resource property and it is displayed on the Console along with the Resource ID that DocumentDB assigned to it. Step 4 − Now call CreateDatabase task from the CreateDocumentClient task after DocumentClient is instantiated. using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { await CreateDatabase(client); } Following is the complete Program.cs file so far. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Newtonsoft.Json; namespace DocumentDBDemo { class Program { private const string EndpointUrl = “https://azuredocdbdemo.documents.azure.com:443/”; private const string AuthorizationKey = “BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/ StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==”; static void Main(string[] args) { try { CreateDocumentClient().Wait(); } catch (Exception e) { Exception baseException = e.GetBaseException(); Console.WriteLine(“Error: {0}, Message: {1}”, e.Message, baseException.Message); } Console.ReadKey(); } private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { await CreateDatabase(client); } } private async static Task CreateDatabase(DocumentClient client) { Console.WriteLine(); Console.WriteLine(“******** Create Database *******”); var databaseDefinition = new Database { Id = “mynewdb” }; var result = await client.CreateDatabaseAsync(databaseDefinition); var database = result.Resource; Console.WriteLine(” Database Id: {0}; Rid: {1}”, database.Id, database.ResourceId); Console.WriteLine(“******** Database Created *******”); } } } When the above code is compiled and executed, you will receive the following output which contains the Database and Resources IDs. ******** Create Database ******* Database Id: mynewdb; Rid: ltpJAA== ******** Database Created ******* Print Page Previous Next Advertisements ”;