Category: documentdb

  • Khóa học miễn phí DocumentDB – Data Types nhận dự án làm có lương

    DocumentDB – Data Types



    JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange and also easy for machines to parse and generate. JSON is at the heart of DocumentDB. We transmit JSON over the wire, we store JSON as JSON, and we index the JSON tree allowing queries on the full JSON document.

    JSON format supports the following data types −

    S.No. Type & Description
    1

    Number

    Double-precision floating-point format in JavaScript

    2

    String

    Double-quoted Unicode with backslash escaping

    3

    Boolean

    True or false

    4

    Array

    An ordered sequence of values

    5

    Value

    It can be a string, a number, true or false, null, etc.

    6

    Object

    An unordered collection of key:value pairs

    7

    Whitespace

    It can be used between any pair of tokens

    8

    Null

    Empty

    Let’s take a look at a simple example DateTime type. Add birth date to the customer class.

    public class Customer {
       [JsonProperty(PropertyName = "id")]
       public string Id { get; set; }
    
       // Must be nullable, unless generating unique values for new customers on client
       [JsonProperty(PropertyName = "name")]
       public string Name { get; set; }
    
       [JsonProperty(PropertyName = "address")]
       public Address Address { get; set; }
    
       [JsonProperty(PropertyName = "birthDate")]
       public DateTime BirthDate { get; set; }
    }
    

    We can store, retrieve, and query using DateTime as shown in the following code.

    private async static Task CreateDocuments(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Create Documents ****");
       Console.WriteLine();
    
       var document3Definition = new Customer {
          Id = "1001",
          Name = "Luke Andrew",
    
          Address = new Address {
             AddressType = "Main Office",
             AddressLine1 = "123 Main Street",
             Location = new Location {
                City = "Brooklyn",
                StateProvinceName = "New York"
             },
             PostalCode = "11229",
             CountryRegionName = "United States"
          },
    
          BirthDate = DateTime.Parse(DateTime.Today.ToString()),
       };
    
       Document document3 = await CreateDocument(client, document3Definition);
       Console.WriteLine("Created document {0} from typed object", document3.Id);
       Console.WriteLine();
    }
    

    When the above code is compiled and executed, and the document is created, you will see that birth date is added now.

    **** Create Documents ****
    Created new document: 1001
    {
       "id": "1001",
       "name": "Luke Andrew",
       "address": {
          "addressType": "Main Office",
          "addressLine1": "123 Main Street",
          "location": {
             "city": "Brooklyn",
             "stateProvinceName": "New York"
          },
          "postalCode": "11229",
          "countryRegionName": "United States"
       },
       "birthDate": "2015-12-14T00:00:00",
       "_rid": "Ic8LAMEUVgAKAAAAAAAAAA==",
       "_ts": 1450113676,
       "_self": "dbs/Ic8LAA==/colls/Ic8LAMEUVgA=/docs/Ic8LAMEUVgAKAAAAAAAAAA==/",
       "_etag": ""00002d00-0000-0000-0000-566efa8c0000"",
       "_attachments": "attachments/"
    }
    Created document 1001 from typed object
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Sorting Records nhận dự án làm có lương

    DocumentDB – Sorting Records



    Microsoft Azure DocumentDB supports querying documents using SQL over JSON documents. You can sort documents in the collection on numbers and strings using an ORDER BY clause in your query. The clause can include an optional ASC/DESC argument to specify the order in which results must be retrieved.

    Let’s take a look at the following example in which we have a JSON document.

    {
       "id": "Food Menu",
       "description": "Grapes, red or green (European type, such as Thompson seedless), raw",
    
       "tags": [
          {
             "name": "grapes"
          },
    
          {
             "name": "red or green (european type"
          },
    
          {
             "name": "such as thompson seedless)"
          },
    
          {
             "name": "raw"
          }
       ],
    
       "foodGroup": "Fruits and Fruit Juices",
    
       "servings": [
          {
             "amount": 1,
             "description": "cup",
             "weightInGrams": 151
          },
    
          {
             "amount": 10,
             "description": "grapes",
             "weightInGrams": 49
          },
    
          {
             "amount": 1,
             "description": "NLEA serving",
             "weightInGrams": 126
          }
       ]
    
    }
    

    Following is the SQL query to sort the result in a descending order.

    SELECT f.description, f.foodGroup,
       f.servings[2].description AS servingDescription,
       f.servings[2].weightInGrams AS servingWeight
    
    FROM f
    ORDER BY f.servings[2].weightInGrams DESC
    

    When the above query is executed, you will receive the following output.

    [
       {
          "description": "Grapes, red or green (European type, such as Thompson
             seedless), raw",
          "foodGroup": "Fruits and Fruit Juices",
          "servingDescription": "NLEA serving",
          "servingWeight": 126
       }
    ]
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Indexing Records nhận dự án làm có lương

    DocumentDB – Indexing Records



    By default, DocumentDB automatically indexes every property in a document as soon as the document is added to the database. However, you can take control and fine tune your own indexing policy that reduces storage and processing overhead when there are specific documents and/or properties that never needs to be indexed.

    The default indexing policy that tells DocumentDB to index every property automatically is suitable for many common scenarios. But you can also implement a custom policy that exercises fine control over exactly what gets indexed and what doesn”t and other functionality with regards to indexing.

    DocumentDB supports the following types of indexing −

    • Hash
    • Range

    Hash

    Hash index enables efficient querying for equality, i.e., while searching for documents where a given property equals an exact value, rather than matching on a range of values like less than, greater than or between.

    You can perform range queries with a hash index, but DocumentDB will not be able to use the hash index to find matching documents and will instead need to sequentially scan each document to determine if it should be selected by the range query.

    You won”t be able to sort your documents with an ORDER BY clause on a property that has just a hash index.

    Range

    Range index defined for the property, DocumentDB allows to efficiently query for documents against a range of values. It also allows you to sort the query results on that property, using ORDER BY.

    DocumentDB allows you to define both a hash and a range index on any or all properties, which enables efficient equality and range queries, as well as ORDER BY.

    Indexing Policy

    Every collection has an indexing policy that dictates which types of indexes are used for numbers and strings in every property of every document.

    • You can also control whether or not documents get indexed automatically as they are added to the collection.

    • Automatic indexing is enabled by default, but you can override that behavior when adding a document, telling DocumentDB not to index that particular document.

    • You can disable automatic indexing so that by default, documents are not indexed when added to the collection. Similarly, you can override this at the document level and instruct DocumentDB to index a particular document when adding it to the collection. This is known as manual indexing.

    Include / Exclude Indexing

    An indexing policy can also define which path or paths should be included or excluded from the index. This is useful if you know that there are certain parts of a document that you never query against and certain parts that you do.

    In these cases, you can reduce indexing overhead by telling DocumentDB to index just those particular portions of each document added to the collection.

    Automatic Indexing

    Let’s take a look at a simple example of automatic indexing.

    Step 1 − First we create a collection called autoindexing and without explicitly supplying a policy, this collection uses the default indexing policy, which means that automatic indexing is enabled on this collection.

    Here we are using ID-based routing for the database self-link so we don”t need to know its resource ID or query for it before creating the collection. We can just use the database ID, which is mydb.

    Step 2 − Now let’s create two documents, both with the last name of Upston.

    private async static Task AutomaticIndexing(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Override Automatic Indexing ****");
    
       // Create collection with automatic indexing
    
       var collectionDefinition = new DocumentCollection {
          Id = "autoindexing"
       };
    
       var collection = await client.CreateDocumentCollectionAsync("dbs/mydb",
          collectionDefinition);
    
       // Add a document (indexed)
       dynamic indexedDocumentDefinition = new {
          id = "MARK",
          firstName = "Mark",
          lastName = "Upston",
          addressLine = "123 Main Street",
          city = "Brooklyn",
          state = "New York",
          zip = "11229",
       };
    
       Document indexedDocument = await client
          .CreateDocumentAsync("dbs/mydb/colls/autoindexing", indexedDocumentDefinition);
    
       // Add another document (request no indexing)
       dynamic unindexedDocumentDefinition = new {
          id = "JANE",
          firstName = "Jane",
          lastName = "Upston",
          addressLine = "123 Main Street",
          city = "Brooklyn",
          state = "New York",
          zip = "11229",
       };
    
       Document unindexedDocument = await client
          .CreateDocumentAsync("dbs/mydb/colls/autoindexing", unindexedDocumentDefinition,
          new RequestOptions { IndexingDirective = IndexingDirective.Exclude });
    
       //Unindexed document won''t get returned when querying on non-ID (or selflink) property
    
       var doeDocs = client.CreateDocumentQuery("dbs/mydb/colls/autoindexing", "SELECT *
          FROM c WHERE c.lastName = ''Doe''").ToList();
    
       Console.WriteLine("Documents WHERE lastName = ''Doe'': {0}", doeDocs.Count);
    
       // Unindexed document will get returned when using no WHERE clause
    
       var allDocs = client.CreateDocumentQuery("dbs/mydb/colls/autoindexing",
          "SELECT * FROM c").ToList();
       Console.WriteLine("All documents: {0}", allDocs.Count);
    
       // Unindexed document will get returned when querying by ID (or self-link) property
    
       Document janeDoc = client.CreateDocumentQuery("dbs/mydb/colls/autoindexing",
          "SELECT * FROM c WHERE c.id = ''JANE''").AsEnumerable().FirstOrDefault();
       Console.WriteLine("Unindexed document self-link: {0}", janeDoc.SelfLink);
    
       // Delete the collection
    
       await client.DeleteDocumentCollectionAsync("dbs/mydb/colls/autoindexing");
    }
    

    This first one, for Mark Upston, gets added to the collection and is then immediately indexed automatically based on the default indexing policy.

    But when the second document for Mark Upston is added, we have passed the request options with IndexingDirective.Exclude which explicitly instructs DocumentDB not to index this document, despite the collection”s indexing policy.

    We have different types of queries for both the documents at the end.

    Step 3 − Let’s call the AutomaticIndexing task from CreateDocumentClient.

    private static async Task CreateDocumentClient() {
       // Create a new instance of the DocumentClient
       using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
          await AutomaticIndexing(client);
       }
    }
    

    When the above code is compiled and executed, you will receive the following output.

    **** Override Automatic Indexing ****
    Documents WHERE lastName = ''Upston'': 1
    All documents: 2
    Unindexed document self-link: dbs/kV5oAA==/colls/kV5oAOEkfQA=/docs/kV5oAOEkfQACA
    AAAAAAAAA==/
    

    As you can see we have two such documents, but the query returns only the one for Mark because the one for Mark isn”t indexed. If we query again, without a WHERE clause to retrieve all the documents in the collection, then we get a result set with both documents and this is because unindexed documents are always returned by queries that have no WHERE clause.

    We can also retrieve unindexed documents by their ID or self-link. So when we query for Mark”s document by his ID, MARK, we see that DocumentDB returns the document even though it isn”t indexed in the collection.

    Manual Indexing

    Let’ take a look at a simple example of manual indexing by overriding automatic indexing.

    Step 1 − First we”ll create a collection called manualindexing and override the default policy by explicitly disabling automatic indexing. This means that, unless we request otherwise, new documents added to this collection will not be indexed.

    private async static Task ManualIndexing(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Manual Indexing ****");
       // Create collection with manual indexing
    
       var collectionDefinition = new DocumentCollection {
          Id = "manualindexing",
          IndexingPolicy = new IndexingPolicy {
             Automatic = false,
          },
       };
    
       var collection = await client.CreateDocumentCollectionAsync("dbs/mydb",
          collectionDefinition);
    
       // Add a document (unindexed)
       dynamic unindexedDocumentDefinition = new {
          id = "MARK",
          firstName = "Mark",
          lastName = "Doe",
          addressLine = "123 Main Street",
          city = "Brooklyn",
          state = "New York",
          zip = "11229",
       };
    
       Document unindexedDocument = await client
          .CreateDocumentAsync("dbs/mydb/colls/manualindexing", unindexedDocumentDefinition);
    
       // Add another document (request indexing)
       dynamic indexedDocumentDefinition = new {
          id = "JANE",
          firstName = "Jane",
          lastName = "Doe",
          addressLine = "123 Main Street",
          city = "Brooklyn",
          state = "New York",
          zip = "11229",
       };
    
       Document indexedDocument = await client.CreateDocumentAsync
          ("dbs/mydb/colls/manualindexing", indexedDocumentDefinition, new RequestOptions {
          IndexingDirective = IndexingDirective.Include });
    
       //Unindexed document won''t get returned when querying on non-ID (or selflink) property
    
       var doeDocs = client.CreateDocumentQuery("dbs/mydb/colls/manualindexing",
          "SELECT * FROM c WHERE c.lastName = ''Doe''").ToList();
       Console.WriteLine("Documents WHERE lastName = ''Doe'': {0}", doeDocs.Count);
    
       // Unindexed document will get returned when using no WHERE clause
    
       var allDocs = client.CreateDocumentQuery("dbs/mydb/colls/manualindexing",
          "SELECT * FROM c").ToList();
       Console.WriteLine("All documents: {0}", allDocs.Count);
    
       // Unindexed document will get returned when querying by ID (or self-link) property
    
       Document markDoc = client
          .CreateDocumentQuery("dbs/mydb/colls/manualindexing",
          "SELECT * FROM c WHERE c.id = ''MARK''")
          .AsEnumerable().FirstOrDefault();
       Console.WriteLine("Unindexed document self-link: {0}", markDoc.SelfLink);
       await client.DeleteDocumentCollectionAsync("dbs/mydb/colls/manualindexing");
    }
    

    Step 2 − Now we will again create the same two documents as before. We will not supply any special request options for Mark”s document this time, because of the collection”s indexing policy, this document will not get indexed.

    Step 3 − Now when we add the second document for Mark, we use RequestOptions with IndexingDirective.Include to tell DocumentDB that it should index this document, which overrides the collection”s indexing policy that says that it shouldn”t.

    We have different types of queries for both the documents at the end.

    Step 4 − Let’s call the ManualIndexing task from CreateDocumentClient.

    private static async Task CreateDocumentClient() {
       // Create a new instance of the DocumentClient
       using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
          await ManualIndexing(client);
       }
    }
    

    When the above code is compiled and executed you will receive the following output.

    **** Manual Indexing ****
    Documents WHERE lastName = ''Upston'': 1
    All documents: 2
    Unindexed document self-link: dbs/kV5oAA==/colls/kV5oANHJPgE=/docs/kV5oANHJPgEBA
    AAAAAAAAA==/
    

    Again, the query returns only one of the two documents, but this time, it returns Jane Doe, which we explicitly requested to be indexed. But again as before, querying without a WHERE clause retrieves all the documents in the collection, including the unindexed document for Mark. We can also query for the unindexed document by its ID, which DocumentDB returns even though it”s not indexed.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Geospatial Data nhận dự án làm có lương

    DocumentDB – Geospatial Data



    Microsoft added geospatial support, which lets you store location data in your documents and perform spatial calculations for distance and intersections between points and polygons.

    • Spatial data describes the position and shape of objects in space.

    • Typically, it can be used to represent the location of a person, a place of interest, or the boundary of a city, or a lake.

    • Common use cases often involve proximity queries. For e.g., “find all universities near my current location”.

    A Point denotes a single position in space which represents the exact location, e.g. street address of particular university. A point is represented in DocumentDB using its coordinate pair (longitude and latitude). Following is an example of JSON point.

    {
       "type":"Point",
       "coordinates":[ 28.3, -10.7 ]
    }
    

    Let’s take a look at a simple example which contains the location of a university.

    {
       "id":"case-university",
       "name":"CASE: Center For Advanced Studies In Engineering",
       "city":"Islamabad",
    
       "location": {
          "type":"Point",
          "coordinates":[ 33.7194136, -73.0964862 ]
       }
    }
    

    To retrieve the university name based on the location, you can use the following query.

    SELECT c.name FROM c
    
    WHERE c.id = "case-university" AND ST_ISVALID({
          "type":"Point",
          "coordinates":[ 33.7194136, -73.0964862 ] })
    

    When the above query is executed you will receive the following output.

    [
       {
          "name": "CASE: Center For Advanced Studies In Engineering"
       }
    ]
    

    Create Document with Geospatial Data in .NET

    You can create a document with geospatial data, let’s take a look at a simple example in which a university document is created.

    private async static Task CreateDocuments(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Create Documents ****");
       Console.WriteLine();
    
       var uniDocument = new UniversityProfile {
          Id = "nust",
          Name = "National University of Sciences and Technology",
          City = "Islamabad",
          Loc = new Point(33.6455715, 72.9903447)
       };
    
       Document document = await CreateDocument(client, uniDocument);
       Console.WriteLine("Created document {0} from typed object", document.Id);
       Console.WriteLine();
    }
    

    Following is the implementation for the UniversityProfile class.

    public class UniversityProfile {
       [JsonProperty(PropertyName = "id")]
       public string Id { get; set; }
    
       [JsonProperty("name")]
       public string Name { get; set; }
    
       [JsonProperty("city")]
       public string City { get; set; }
    
       [JsonProperty("location")]
       public Point Loc { get; set; }
    }
    

    When the above code is compiled and executed, you will receive the following output.

    **** Create Documents ****
    Created new document: nust
    {
       "id": "nust",
       "name": "National University of Sciences and Technology",
       "city": "Islamabad",
       "location": {
          "type": "Point",
          "coordinates": [
             33.6455715,
             72.9903447
          ]
       },
       "_rid": "Ic8LAMEUVgANAAAAAAAAAA==",
       "_ts": 1450200910,
       "_self": "dbs/Ic8LAA==/colls/Ic8LAMEUVgA=/docs/Ic8LAMEUVgANAAAAAAAAAA==/",
       "_etag": ""00004100-0000-0000-0000-56704f4e0000"",
       "_attachments": "attachments/"
    }
    Created document nust from typed object
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Partitioning nhận dự án làm có lương

    DocumentDB – Partitioning



    When your database starts to grow beyond 10GB, you can scale out simply by creating new collections and then spreading or partitioning your data across more and more collections.

    Sooner or later a single collection, which has a 10GB capacity, will not be enough to contain your database. Now 10GB may not sound like a very large number, but remember that we”re storing JSON documents, which is just plain text and you can fit a lot of plain text documents in 10GB, even when you consider the storage overhead for the indexes.

    Storage isn”t the only concern when it comes to scalability. The maximum throughput available on a collection is two and a half thousand request units per second that you get with an S3 collection. Hence, if you need higher throughput, then you will also need to scale out by partitioning with multiple collections. Scale out partitioning is also called horizontal partitioning.

    There are many approaches that can be used for partitioning data with Azure DocumentDB. Following are most common strategies −

    • Spillover Partitioning
    • Range Partitioning
    • Lookup Partitioning
    • Hash Partitioning

    Spillover Partitioning

    Spillover partitioning is the simplest strategy because there is no partition key. It”s often a good choice to start with when you”re unsure about a lot of things. You might not know if you”ll even ever need to scale out beyond a single collection or how many collections you may need to add or how fast you may need to add them.

    • Spillover partitioning starts with a single collection and there is no partition key.

    • The collection starts to grow and then grows some more, and then some more, until you start getting close to the 10GB limit.

    • When you reach 90 percent capacity, you spill over to a new collection and start using it for new documents.

    • Once your database scales out to a larger number of collections, you”ll probably want to shift to a strategy that”s based on a partition key.

    • When you do that you”ll need to rebalance your data by moving documents to different collections based on whatever strategy you”re migrating to.

    Range Partitioning

    One of the most common strategies is range partitioning. With this approach you determine the range of values that a document”s partition key might fall in and direct the document to a collection corresponding to that range.

    • Dates are very typically used with this strategy where you create a collection to hold documents that fall within the defined range of dates. When you define ranges that are small enough, where you”re confident that no collection will ever exceed its 10GB limit. For example, there may be a scenario where a single collection can reasonably handle documents for an entire month.

    • It may also be the case that most users are querying for current data, which would be data for this month or perhaps last month, but users are rarely searching for much older data. So you start off in June with an S3 collection, which is the most expensive collection you can buy and delivers the best throughput you can get.

    • In July you buy another S3 collection to store the July data and you also scale the June data down to a less-expensive S2 collection. Then in August, you get another S3 collection and scale July down to an S2 and June all the way down to an S1. It goes, month after month, where you”re always keeping the current data available for high throughput and older data is kept available at lower throughputs.

    • As long as the query provides a partition key, only the collection that needs to be queried will get queried and not all the collections in the database like it happens with spillover partitioning.

    Lookup Partitioning

    With lookup partitioning you can define a partition map that routes documents to specific collections based on their partition key. For example, you could partition by region.

    • Store all US documents in one collection, all European documents in another collection, and all documents from any other region in a third collection.

    • Use this partition map and a lookup partition resolver can figure out which collection to create a document in and which collections to query, based on the partition key, which is the region property contained in each document.

    Hash Partitioning

    In hash partitioning, partitions are assigned based on the value of a hash function, allowing you to evenly distribute requests and data across a number of partitions.

    This is commonly used to partition data produced or consumed from a large number of distinct clients, and is useful for storing user profiles, catalog items, etc.

    Let’s take a look at a simple example of range partitioning using the RangePartitionResolver supplied by the .NET SDK.

    Step 1 − Create a new DocumentClient and we will create two collections in CreateCollections task. One will contain documents for users that have user IDs beginning with A through M and the other for user IDs N through Z.

    private static async Task CreateCollections(DocumentClient client) {
       await client.CreateDocumentCollectionAsync(“dbs/myfirstdb”, new DocumentCollection {
          Id = “CollectionAM” });
    
       await client.CreateDocumentCollectionAsync(“dbs/myfirstdb”, new DocumentCollection {
          Id = “CollectionNZ” });
    }
    

    Step 2 − Register the range resolver for the database.

    Step 3 − Create a new RangePartitionResolver<string>, which is the datatype of our partition key. The constructor takes two parameters, the property name of the partition key and a dictionary that is the shard map or partition map, which is just a list of the ranges and corresponding collections that we are predefining for the resolver.

    private static void RegisterRangeResolver(DocumentClient client) {
    
       //Note: uffff is the largest UTF8 value, so Mufff includes all strings that start with M.
    
       var resolver = new RangePartitionResolver<string>(
          "userId", new Dictionary<Range<string>, string>() {
          { new Range<string>("A", "Muffff"), "dbs/myfirstdb/colls/CollectionAM" },
          { new Range<string>("N", "Zuffff"), "dbs/myfirstdb/colls/CollectionNZ" },
       });
    
       client.PartitionResolvers["dbs/myfirstdb"] = resolver;
     }
    

    It”s necessary to encode the largest possible UTF-8 value here. Or else the first range wouldn”t match on any Ms except the one single M, and likewise for Z in the second range. So, you can just think of this encoded value here as a wildcard for matching on the partition key.

    Step 4 − After creating the resolver, register it for the database with the current DocumentClient. To do that just assign it to the PartitionResolver”s dictionary property.

    We”ll create and query for documents against the database, not a collection as you normally do, the resolver will use this map to route requests to the appropriate collections.

    Now let”s create some documents. First we will create one for userId Kirk, and then one for Spock.

    private static async Task CreateDocumentsAcrossPartitions(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Create Documents Across Partitions ****");
    
       var kirkDocument = await client.CreateDocumentAsync("dbs/myfirstdb", new { userId =
          "Kirk", title = "Captain" });
       Console.WriteLine("Document 1: {0}", kirkDocument.Resource.SelfLink);
    
       var spockDocument = await client.CreateDocumentAsync("dbs/myfirstdb", new { userId =
          "Spock", title = "Science Officer" });
       Console.WriteLine("Document 2: {0}", spockDocument.Resource.SelfLink);
    }
    

    The first parameter here is a self-link to the database, not a specific collection. This is not possible without a partition resolver, but with one it just works seamlessly.

    Both documents were saved to the database myfirstdb, but we know that Kirk is being stored in the collection for A through M and Spock is being stored in the collection for N to Z, if our RangePartitionResolver is working properly.

    Let’s call these from the CreateDocumentClient task as shown in the following code.

    private static async Task CreateDocumentClient() {
       // Create a new instance of the DocumentClient
       using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
          await CreateCollections(client);
          RegisterRangeResolver(client);
          await CreateDocumentsAcrossPartitions(client);
       }
    }
    

    When the above code is executed, you will receive the following output.

    **** Create Documents Across Partitions ****
    Document 1: dbs/Ic8LAA==/colls/Ic8LAO2DxAA=/docs/Ic8LAO2DxAABAAAAAAAAAA==/
    Document 2: dbs/Ic8LAA==/colls/Ic8LAP12QAE=/docs/Ic8LAP12QAEBAAAAAAAAAA==/
    

    As seen the self-links of the two documents have different resource IDs because they exist in two separate collections.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Data Migration nhận dự án làm có lương

    DocumentDB – Data Migration



    With the DocumentDB Data Migration tool, you can easily migrate data to DocumentDB. The DocumentDB Data Migration Tool is a free and open source utility you can download from the Microsoft Download Center

    The Migration Tool supports many data sources, some of them are listed below −

    • MongoDB
    • Azure Table Storage
    • Amazon DynamoDB
    • HBase, and even other DocumentDB databases

    After downloading the DocumentDB Data Migration tool, extract the zip file.

    You can see two executables in this folder as shown in the following screenshot.

    Executable Files

    First, there is dt.exe, which is the console version with a command line interface, and then there is dtui.exe, which is the desktop version with a graphical user interface.

    Let”s launch the GUI version.

    Launch GUI version

    You can see the Welcome page. Click ‘Next’ for the Source Information page.

    Source Information page

    Here”s where you configure your data source, and you can see the many supported choices from the dropdown menu.

    Specify Source Information

    When you make a selection, the rest of the Source Information page changes accordingly.

    It is very easy to import data to DocumentDB using the DocumentDB Data Migration Tool. We recommend you exercise the above examples and use the other data files as well.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Useful Resources nhận dự án làm có lương

    DocumentDB – Useful Resources



    The following resources contain additional information on DocumentDB. Please use them to get more in-depth knowledge on this topic.

    Useful Links on DocumentDB

    • − Reference for DocumentDB.

    • − Introduction Reference for DocumentDB.

    • − Wikipedia Reference for DocumentDB.

    Useful Books on DocumentDB

    To enlist your site on this page, please drop an email to contact@tutorialspoint.com


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Discussion nhận dự án làm có lương

    Discuss DocumentDB



    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.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Drop Databases nhận dự án làm có lương

    DocumentDB – Drop Databases



    You can drop a database or databases from the portal as well as from the code by using .Net SDK. Here, we will discuss, in a step-wise manner, how to drop a database in DocumentDB.

    Step 1 − Go to your DocumentDB account on Azure portal. For the purpose of demo, I have added two more databases as seen in the following screenshot.

    Drop Databases

    Step 2 − To drop any database, you need to click that database. Let’s select tempdb, you will see the following page, select the ‘Delete Database’ option.

    Delete Database

    Step 3 − It will display the confirmation message, now click the ‘Yes’ button.

    Confirmation Message

    You will see that the tempdb is no more available in your dashboard.

    TempDB Deleted

    You can also delete databases from your code using .Net SDK. To do following are the steps.

    Step 1 − Let”s delete the database by specifying the ID of the database we want to delete, but we need its SelfLink.

    Step 2 − We are calling the CreateDatabaseQuery like before, but this time we are actually supplying a query to return just the one database with the ID tempdb1.

    private async static Task DeleteDatabase(DocumentClient client) {
       Console.WriteLine("******** Delete Database ********");
       Database database = client
          .CreateDatabaseQuery("SELECT * FROM c WHERE c.id = ''tempdb1''")
          .AsEnumerable()
          .First();
       await client.DeleteDatabaseAsync(database.SelfLink);
    }
    

    Step 3 − This time, we can call AsEnumerable instead of ToList() because we don”t actually need a list object. Expecting only result, calling AsEnumerable is sufficient so that we can get the first database object returned by the query with First(). This is the database object for tempdb1 and it has a SelfLink that we can use to call DeleteDatabaseAsync which deletes the database.

    Step 4 − You also need to call DeleteDatabase task from the CreateDocumentClient task after DocumentClient is instantiated.

    Step 5 − To view the list of databases after deleting the specified database, let’s call GetDatabases method again.

    using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
       //await CreateDatabase(client);
    
       GetDatabases(client);
       await DeleteDatabase(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);
                await DeleteDatabase(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);
          }
    
          private async static Task DeleteDatabase(DocumentClient client) {
             Console.WriteLine();
             Console.WriteLine("******** Delete Database ********");
    
             Database database = client
                .CreateDatabaseQuery("SELECT * FROM c WHERE c.id = ''tempdb1''")
                .AsEnumerable()
                .First();
             await client.DeleteDatabaseAsync(database.SelfLink);
          }
    
       }
    }
    

    When the above code is compiled and executed, you will receive the following output which contains the Database and Resources IDs of the three databases and total number of databases.

    ******** Get Databases List ********
     Database Id: myfirstdb; Rid: Ic8LAA==
     Database Id: mynewdb; Rid: ltpJAA==
     Database Id: tempdb1; Rid: 06JjAA==
    
    Total databases: 3
    
    ******** Delete Database ********
    
    ******** Get Databases List ********
     Database Id: myfirstdb; Rid: Ic8LAA==
     Database Id: mynewdb; Rid: ltpJAA==
    
    Total databases: 2
    

    After deleting the database, you will also see at the end that only two databases are left in DocumentDB account.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Home nhận dự án làm có lương

    DocumentDB tutorial

    DocumentDB Tutorial







    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.

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc