Category: documentdb Sql

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

    DocumentDB SQL – Array Creation



    In DocumentDB SQL, Microsoft has added a key feature with the help of which we can easily create an array. It means when we run a query, then as a result it will create an array of collection similar to JSON object as a result of query.

    Let’s consider the same documents as in the previous examples.

    Following is the AndersenFamily document.

    {
       "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
    }
    

    Following is the SmithFamily document.

    {
       "id": "SmithFamily",
    
       "parents": [
          { "familyName": "Smith", "givenName": "James" },
          { "familyName": "Curtis", "givenName": "Helen" }
       ],
    
       "children": [
          {
             "givenName": "Michelle",
             "gender": "female",
             "grade": 1
          },
    
          {
             "givenName": "John",
             "gender": "male",
             "grade": 7,
    
             "pets": [
                { "givenName": "Tweetie", "type": "Bird" }
             ]
          }
       ],
    
       "location": {
          "state": "NY",
          "county": "Queens",
          "city": "Forest Hills"
       },
    
       "isRegistered": true
    }
    

    Following is the WakefieldFamily document.

    {
       "id": "WakefieldFamily",
    
       "parents": [
          { "familyName": "Wakefield", "givenName": "Robin" },
          { "familyName": "Miller", "givenName": "Ben" }
       ],
    
       "children": [
          {
             "familyName": "Merriam",
             "givenName": "Jesse",
             "gender": "female",
             "grade": 6,
    
             "pets": [
                { "givenName": "Charlie Brown", "type": "Dog" },
                { "givenName": "Tiger", "type": "Cat" },
                { "givenName": "Princess", "type": "Cat" }
             ]
          },
    
          {
             "familyName": "Miller",
             "givenName": "Lisa",
             "gender": "female",
             "grade": 3,
    
             "pets": [
                { "givenName": "Jake", "type": "Snake" }
             ]
          }
       ],
    
       "location": { "state": "NY", "county": "Manhattan", "city": "NY" },
       "isRegistered": false
    }
    

    Let’s take a look at an example.

    Array Creation

    Following is the query which will return the family name and address of each family.

    SELECT f.id AS FamilyName,
    [f.location.city, f.location.county, f.location.state] AS Address
    FROM Families f
    

    As can be seen city, county and state fields are enclosed in square brackets, which will create an array and this array is named Address. When the above query is executed, it produces the following output.

    [
       {
          "FamilyName": "WakefieldFamily",
          "Address": [
             "NY",
             "Manhattan",
             "NY"
          ]
       },
    
       {
          "FamilyName": "SmithFamily",
          "Address": [
             "Forest Hills",
             "Queens",
             "NY"
          ]
       },
    
       {
          "FamilyName": "AndersenFamily",
          "Address": [
             "Seattle",
             "King",
             "WA"
          ]
       }
    ]
    

    The city, county, and state information are added in the Address array in the above output.


    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í User-Defined Functions nhận dự án làm có lương

    DocumentDB SQL – User-Defined Functions



    DocumentDB SQL provides support for User-Defined Functions (UDFs). UDFs are just another kind of JavaScript functions you can write and these work pretty much as you”d expect. You can create UDFs to extend the query language with custom business logic that you can reference in your queries.

    The DocumentDB SQL syntax is extended to support custom application logic using these UDFs. UDFs can be registered with DocumentDB and then be referenced as part of a SQL query.

    Let’s consider the following three documents for this example.

    AndersenFamily document is as follows.

    {
       "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
    }
    

    SmithFamily document is as follows.

    {
       "id": "SmithFamily",
    
       "parents": [
          { "familyName": "Smith", "givenName": "James" },
          { "familyName": "Curtis", "givenName": "Helen" }
       ],
    
       "children": [
          {
             "givenName": "Michelle",
             "gender": "female",
             "grade": 1
          },
    
          {
             "givenName": "John",
             "gender": "male",
             "grade": 7,
    
             "pets": [
                { "givenName": "Tweetie", "type": "Bird" }
             ]
          }
       ],
    
       "location": {
          "state": "NY",
          "county": "Queens",
          "city": "Forest Hills"
       },
    
       "isRegistered": true
    }
    

    WakefieldFamily document is as follows.

    {
       "id": "WakefieldFamily",
    
       "parents": [
          { "familyName": "Wakefield", "givenName": "Robin" },
          { "familyName": "Miller", "givenName": "Ben" }
       ],
    
       "children": [
          {
             "familyName": "Merriam",
             "givenName": "Jesse",
             "gender": "female",
             "grade": 6,
    
             "pets": [
                { "givenName": "Charlie Brown", "type": "Dog" },
                { "givenName": "Tiger", "type": "Cat" },
                { "givenName": "Princess", "type": "Cat" }
             ]
          },
    
          {
             "familyName": "Miller",
             "givenName": "Lisa",
             "gender": "female",
             "grade": 3,
    
             "pets": [
                { "givenName": "Jake", "type": "Snake" }
             ]
          }
       ],
    
       "location": { "state": "NY", "county": "Manhattan", "city": "NY" },
       "isRegistered": false
    }
    

    Let’s take a look at an example where we will create some simple UDFs.

    Following is the implementation of CreateUserDefinedFunctions.

    private async static Task CreateUserDefinedFunctions(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Create User Defined Functions ****");
       Console.WriteLine();
    
       await CreateUserDefinedFunction(client, "udfRegEx");
    }
    

    We have a udfRegEx, and in CreateUserDefinedFunction we get its JavaScript code from our local file. We construct the definition object for the new UDF, and call CreateUserDefinedFunctionAsync with the collection”s SelfLink and the udfDefinition object as shown in the following code.

    private async static Task<UserDefinedFunction>
    CreateUserDefinedFunction(DocumentClient client, string udfId) {
       var udfBody = File.ReadAllText(@"....Server" + udfId + ".js");
    
       var udfDefinition = new UserDefinedFunction {
          Id = udfId,
          Body = udfBody
       };
    
       var result = await client
          .CreateUserDefinedFunctionAsync(_collection.SelfLink, udfDefinition);
       var udf = result.Resource;
    
       Console.WriteLine("Created user defined function {0}; RID: {1}",
          udf.Id, udf.ResourceId);
    
       return udf;
    }
    

    We get back the new UDF from the resource property of the result and return it back up to the caller. To display the existing UDF, following is the implementation of ViewUserDefinedFunctions. We call CreateUserDefinedFunctionQuery and loop through them as usual.

    private static void ViewUserDefinedFunctions(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** View UDFs ****");
       Console.WriteLine();
    
       var udfs = client
          .CreateUserDefinedFunctionQuery(_collection.UserDefinedFunctionsLink)
          .ToList();
    
       foreach (var udf in udfs) {
          Console.WriteLine("User defined function {0}; RID: {1}", udf.Id, udf.ResourceId);
       }
    }
    

    DocumentDB SQL doesn”t provide built-in functions to search for substrings or for regular expressions, hence the following little one-liner fills that gap which is a JavaScript function.

    function udfRegEx(input, regex) {
       return input.match(regex);
    }
    

    Given the input string in the first parameter, use JavaScript”s built-in regular expression support passing in the pattern matching string in the second parameter into .match. We can run a substring query to find all stores with the word Andersen in their lastName property.

    private static void Execute_udfRegEx(DocumentClient client) {
       var sql = "SELECT c.name FROM c WHERE udf.udfRegEx(c.lastName, ''Andersen'') != null";
    
       Console.WriteLine();
       Console.WriteLine("Querying for Andersen");
    
       var documents = client.CreateDocumentQuery(_collection.SelfLink, sql).ToList();
       Console.WriteLine("Found {0} Andersen:", documents.Count);
    
       foreach (var document in documents) {
          Console.WriteLine("Id: {0}, Name: {1}", document.id, document.lastName);
       }
    }
    

    Note that we must qualify every UDF reference with the prefix udf. We just passed the SQL along to CreateDocumentQuery like any ordinary query. Finally, let’s call the above queries from 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();
          collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
             "SELECT * FROM c WHERE c.id = ''Families''").AsEnumerable().First();
    
          await CreateUserDefinedFunctions(client);
    
          ViewUserDefinedFunctions(client);
    
          Execute_udfRegEx(client);
       }
    }
    

    When the above code is executed, it produces the following output.

    **** Create User Defined Functions ****
    Created user defined function udfRegEx; RID: kV5oANVXnwAlAAAAAAAAYA==
    **** View UDFs ****
    User defined function udfRegEx; RID: kV5oANVXnwAlAAAAAAAAYA==
    Querying for Andersen
    Found 1 Andersen:
     Id: AndersenFamily, Name: Andersen
    

    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í JavaScript Integration nhận dự án làm có lương

    DocumentDB SQL – JavaScript Integration



    These days JavaScript is everywhere, and not just in browsers. DocumentDB embraces JavaScript as a sort of modern day T-SQL and supports the transactional execution of JavaScript logic natively, right inside the database engine. DocumentDB provides a programming model for executing JavaScript-based application logic directly on the collections in terms of stored procedures and triggers.

    Let’s take a look at an example where we create a simple store procedure. Following are the steps −

    Step 1 − Create a new console applications.

    Step 2 − Add in the .NET SDK from NuGet. We are using the .NET SDK here, which means that we”ll be writing some C# code to create, execute, and then delete our stored procedure, but the stored procedure itself gets written in JavaScript.

    Step 3 − Right-click on the project in Solution explorer.

    Step 4 − Add a new JavaScript file for the stored procedure and call it HelloWorldStoreProce.js

    JavaScript Stored Procedure

    Every stored procedure is just a JavaScript function so we”ll create a new function and naturally we”ll also name this function HelloWorldStoreProce. It doesn”t matter if we give the function a name at all. DocumentDB will only refer to this stored procedure by the Id that we provide when we create it.

    function HelloWorldStoreProce() {
       var context = getContext();
       var response = context.getResponse();
       response.setBody(''Hello, and welcome to DocumentDB!'');
    }
    

    All the stored procedure does is obtain the response object from the context and call its setBody method to return a string to the caller. In C# code, we will create the stored procedure, execute it, and then delete it.

    Stored procedures are scoped per collection, therefore we will need the SelfLink of the collection to create the stored procedure.

    Step 5 − First query for the myfirstdb database and then for the MyCollection collection.

    Creating a stored procedure is just like creating any other resource in DocumentDB.

    private async static Task SimpleStoredProcDemo() {
       var endpoint = "https://azuredocdbdemo.documents.azure.com:443/";
       var masterKey =
          "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";
    
       using (var client = new DocumentClient(new Uri(endpoint), masterKey)) {
          // Get database
          Database database = client
             .CreateDatabaseQuery("SELECT * FROM c WHERE c.id = ''myfirstdb''")
             .AsEnumerable()
             .First();
    
          // Get collection
          DocumentCollection collection = client
             .CreateDocumentCollectionQuery(database.CollectionsLink, "SELECT * FROM
             c WHERE c.id = ''MyCollection''")
             .AsEnumerable()
             .First();
    
          // Create stored procedure
          var sprocBody = File.ReadAllText(@"....HelloWorldStoreProce.js");
    
          var sprocDefinition = new StoredProcedure {
             Id = "HelloWorldStoreProce",
             Body = sprocBody
          };
    
          StoredProcedure sproc = await client.
             CreateStoredProcedureAsync(collection.SelfLink, sprocDefinition);
          Console.WriteLine("Created stored procedure {0} ({1})",
             sproc.Id, sproc.ResourceId);
    
          // Execute stored procedure
          var result = await client.ExecuteStoredProcedureAsync(sproc.SelfLink);
          Console.WriteLine("Executed stored procedure; response = {0}", result.Response);
    
          // Delete stored procedure
          await client.DeleteStoredProcedureAsync(sproc.SelfLink);
          Console.WriteLine("Deleted stored procedure {0} ({1})",
             sproc.Id, sproc.ResourceId);
       }
    }
    

    Step 6 − First create a definition object with the Id for the new resource and then call one of the Create methods on the DocumentClient object. In the case of a stored procedure, the definition includes the Id and the actual JavaScript code that you want to ship over to the server.

    Step 7 − Call File.ReadAllText to extract the stored procedure code out of the JS file.

    Step 8 − Assign the stored procedure code to the body property of the definition object.

    As far as DocumentDB is concerned, the Id we specify here, in the definition, is the name of the stored procedure, regardless of what we actually name the JavaScript function.

    Nevertheless when creating stored procedures and other server-side objects, it is recommended that we name JavaScript functions and that those function names do match the Id that we have set in the definition for DocumentDB.

    Step 9 − Call CreateStoredProcedureAsync, passing in the SelfLink for the MyCollection collection and the stored procedure definition. This creates the stored procedure and ResourceId that DocumentDB assigned to it.

    Step 10 − Call the stored procedure. ExecuteStoredProcedureAsync takes a type parameter that you set to the expected data type of the value returned by the stored procedure, which you can specify simply as an object if you want a dynamic object returned. That is an object whose properties will be bound at run-time.

    In this example we know that our stored procedure is just returning a string and so we call ExecuteStoredProcedureAsync<string>.

    Following is the complete implementation of Program.cs file.

    using Microsoft.Azure.Documents;
    using Microsoft.Azure.Documents.Client;
    using Microsoft.Azure.Documents.Linq;
    
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DocumentDBStoreProce {
       class Program {
          private static void Main(string[] args) {
             Task.Run(async () => {
                await SimpleStoredProcDemo();
             }).Wait();
          }
    
          private async static Task SimpleStoredProcDemo() {
             var endpoint = "https://azuredocdbdemo.documents.azure.com:443/";
             var masterKey =
                "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";
    
             using (var client = new DocumentClient(new Uri(endpoint), masterKey)) {
                // Get database
                Database database = client
                   .CreateDatabaseQuery("SELECT * FROM c WHERE c.id = ''myfirstdb''")
                   .AsEnumerable()
                   .First();
    
                // Get collection
                DocumentCollection collection = client
                   .CreateDocumentCollectionQuery(database.CollectionsLink,
                   "SELECT * FROM c WHERE c.id = ''MyCollection''")
                   .AsEnumerable()
                   .First();
    
                // Create stored procedure
                var sprocBody = File.ReadAllText(@"....HelloWorldStoreProce.js");
    
                var sprocDefinition = new StoredProcedure {
                   Id = "HelloWorldStoreProce",
                   Body = sprocBody
                };
    
                StoredProcedure sproc = await client
                   .CreateStoredProcedureAsync(collection.SelfLink, sprocDefinition);
    
                Console.WriteLine("Created stored procedure {0} ({1})", sproc
                   .Id, sproc.ResourceId);
    
                // Execute stored procedure
                var result = await client
                   .ExecuteStoredProcedureAsync<string>(sproc.SelfLink);
                Console.WriteLine("Executed stored procedure; response = {0}",
                   result.Response);
    
                // Delete stored procedure
                await client.DeleteStoredProcedureAsync(sproc.SelfLink);
                Console.WriteLine("Deleted stored procedure {0} ({1})",
                   sproc.Id, sproc.ResourceId);
             }
          }
       }
    }
    

    When the above code is executed, it produces the following output.

    Created stored procedure HelloWorldStoreProce (Ic8LAMEUVgACAAAAAAAAgA==)
    
    Executed stored procedure; response = Hello, and welcome to DocumentDB!
    

    As seen in the above output, the response property has the “Hello, and welcome to DocumentDB!” returned by our stored procedure.


    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í Composite SQL Queries nhận dự án làm có lương

    DocumentDB SQL – Composite SQL Queries



    Composite Query enables you to combine data from existing queries and then apply filters, aggregates, and so on before presenting the report results, which show the combined data set. Composite Query retrieves multiple levels of related information on existing queries and presents the combined data as a single and flattened query result.

    Using Composite Query, you also have the option to −

    • Select the SQL pruning option to remove tables and fields that are not needed based on users’ attribute selections.

    • Set the ORDER BY and GROUP BY clauses.

    • Set the WHERE clause as a filter over the result set of a composite query.

    The above operators can be composed to form more powerful queries. Since DocumentDB supports nested collections, the composition can either be concatenated or nested.

    Let’s consider the following documents for this example.

    AndersenFamily document is as follows.

    {
       "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
    }
    

    SmithFamily document is as follows.

    {
       "id": "SmithFamily",
    
       "parents": [
          { "familyName": "Smith", "givenName": "James" },
          { "familyName": "Curtis", "givenName": "Helen" }
       ],
    
       "children": [
          {
             "givenName": "Michelle",
             "gender": "female",
             "grade": 1
          },
    
          {
             "givenName": "John",
             "gender": "male",
             "grade": 7,
    
             "pets": [
                { "givenName": "Tweetie", "type": "Bird" }
             ]
          }
       ],
    
       "location": {
          "state": "NY",
          "county": "Queens",
          "city": "Forest Hills"
       },
    
       "isRegistered": true
    }
    

    WakefieldFamily document is as follows.

    {
       "id": "WakefieldFamily",
    
       "parents": [
          { "familyName": "Wakefield", "givenName": "Robin" },
          { "familyName": "Miller", "givenName": "Ben" }
       ],
    
       "children": [
          {
             "familyName": "Merriam",
             "givenName": "Jesse",
             "gender": "female",
             "grade": 6,
    
             "pets": [
                { "givenName": "Charlie Brown", "type": "Dog" },
                { "givenName": "Tiger", "type": "Cat" },
                { "givenName": "Princess", "type": "Cat" }
             ]
          },
    
          {
             "familyName": "Miller",
             "givenName": "Lisa",
             "gender": "female",
             "grade": 3,
    
             "pets": [
                { "givenName": "Jake", "type": "Snake" }
             ]
          }
       ],
    
       "location": { "state": "NY", "county": "Manhattan", "city": "NY" },
       "isRegistered": false
    }
    

    Let’s take a look at an example of concatenated query.

    Concatenated Query

    Following is the query which will retrieve the id and location of the family where the first child givenName is Michelle.

    SELECT f.id,f.location
    FROM Families f
    WHERE f.children[0].givenName = "Michelle"
    

    When the above query is executed, it produces the following output.

    [
       {
          "id": "SmithFamily",
          "location": {
             "state": "NY",
             "county": "Queens",
             "city": "Forest Hills"
          }
       }
    ]
    

    Let’s consider another example of concatenated query.

    Concatenated Queries

    Following is the query which will return all the documents where the first child grade greater than 3.

    SELECT *
    FROM Families f
    WHERE ({grade: f.children[0].grade}.grade > 3)
    

    When the above query is executed, it produces the following output.

    [
       {
          "id": "WakefieldFamily",
          "parents": [
             {
                "familyName": "Wakefield",
                "givenName": "Robin"
             },
    
             {
                "familyName": "Miller",
                "givenName": "Ben"
             }
          ],
    
          "children": [
             {
                "familyName": "Merriam",
                "givenName": "Jesse",
                "gender": "female",
                "grade": 6,
    
                "pets": [
                   {
                      "givenName": "Charlie Brown",
                      "type": "Dog"
                   },
    
                   {
                      "givenName": "Tiger",
                      "type": "Cat"
                   },
    
                   {
                      "givenName": "Princess",
                      "type": "Cat"
                   }
                ]
             },
    
             {
                "familyName": "Miller",
                "givenName": "Lisa",
                "gender": "female",
                "grade": 3,
    
                "pets": [
                   {
                      "givenName": "Jake",
                      "type": "Snake"
                   }
                ]
             }
          ],
    
          "location": {
             "state": "NY",
             "county": "Manhattan",
             "city": "NY"
          },
    
          "isRegistered": false,
          "_rid": "Ic8LAJFujgECAAAAAAAAAA==",
          "_ts": 1450541623,
          "_self": "dbs/Ic8LAA==/colls/Ic8LAJFujgE=/docs/Ic8LAJFujgECAAAAAAAAAA==/",
          "_etag": ""00000500-0000-0000-0000-567582370000"",
          "_attachments": "attachments/"
       },
    
       {
          "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,
          "_rid": "Ic8LAJFujgEEAAAAAAAAAA==",
          "_ts": 1450541624,
          "_self": "dbs/Ic8LAA==/colls/Ic8LAJFujgE=/docs/Ic8LAJFujgEEAAAAAAAAAA==/",
          "_etag": ""00000700-0000-0000-0000-567582380000"",
          "_attachments": "attachments/"
       }
    ]
    

    Let’s take a look at an example of nested queries.

    Nested Queries

    Following is the query which will iterate all the parents and then return the document where familyName is Smith.

    SELECT *
    FROM p IN Families.parents
    WHERE p.familyName = "Smith"
    

    When the above query is executed, it produces the following output.

    [
       {
          "familyName": "Smith",
          "givenName": "James"
       }
    ]
    

    Let’s consider another example of nested query.

    Nested Query

    Following is the query which will return all the familyName.

    SELECT VALUE p.familyName
    FROM Families f
    JOIN p IN f.parents
    

    When the above query is executed, it produces he following output.

    [
       "Wakefield",
       "Miller",
       "Smith",
       "Curtis"
    ]
    

    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 SQL – Home nhận dự án làm có lương

    DocumentDB SQL Tutorial

    DocumentDB SQL 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 talks about querying documents using the special version of SQL supported by DocumentDB with illustrative examples.

    Audience

    This tutorial is designed for developers who want to get acquainted with how to query DocumentDB using a familiar Structured Query Language (SQL).

    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

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

    DocumentDB SQL – Operators



    An operator is a reserved word or a character used primarily in an SQL WHERE clause to perform operation(s), such as comparisons and arithmetic operations. DocumentDB SQL also supports a variety of scalar expressions. The most commonly used are binary and unary expressions.

    The following SQL operators are currently supported and can be used in queries.

    SQL Comparison Operators

    Following is a list of all the comparison operators available in DocumentDB SQL grammar.

    S.No. Operators & Description
    1

    =

    Checks if the values of two operands are equal or not. If yes, then condition becomes true.

    2

    !=

    Checks if the values of two operands are equal or not. If values are not equal then condition becomes true.

    3

    <>

    Checks if the values of two operands are equal or not. If values are not equal then condition becomes true.

    4

    >

    Checks if the value of left operand is greater than the value of right operand. If yes, then condition becomes true.

    5

    <

    Checks if the value of left operand is less than the value of right operand. If yes, then condition becomes true.

    6

    >=

    Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then condition becomes true.

    7

    <=

    Checks if the value of left operand is less than or equal to the value of right operand. If yes, then condition becomes true.

    SQL Logical Operators

    Following is a list of all the logical operators available in DocumentDB SQL grammar.

    S.No. Operators & Description
    1

    AND

    The AND operator allows the existence of multiple conditions in an SQL statement”s WHERE clause.

    2

    BETWEEN

    The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value.

    3

    IN

    The IN operator is used to compare a value to a list of literal values that have been specified.

    4

    OR

    The OR operator is used to combine multiple conditions in an SQL statement”s WHERE clause.

    5

    NOT

    The NOT operator reverses the meaning of the logical operator with which it is used. For example, NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.

    SQL Arithmetic Operators

    Following is a list of all the arithmetic operators available in DocumentDB SQL grammar.

    S.No. Operators & Description
    1

    +

    Addition − Adds values on either side of the operator.

    2

    Subtraction − Subtracts the right hand operand from the left hand operand.

    3

    *

    Multiplication − Multiplies values on either side of the operator.

    4

    /

    Division − Divides the left hand operand by the right hand operand.

    5

    %

    Modulus − Divides the left hand operand by the right hand operand and returns the remainder.

    We will consider the same documents in this example as well. Following is the AndersenFamily document.

    {
       "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
    }
    

    Following is the SmithFamily document.

    {
       "id": "SmithFamily",
    
       "parents": [
          { "familyName": "Smith", "givenName": "James" },
          { "familyName": "Curtis", "givenName": "Helen" }
       ],
    
       "children": [
          {
             "givenName": "Michelle",
             "gender": "female",
             "grade": 1
          },
    
          {
             "givenName": "John",
             "gender": "male",
             "grade": 7,
    
             "pets": [
                { "givenName": "Tweetie", "type": "Bird" }
             ]
          }
       ],
    
       "location": {
          "state": "NY",
          "county": "Queens",
          "city": "Forest Hills"
       },
    
       "isRegistered": true
    }
    

    Following is the WakefieldFamily document.

    {
       "id": "WakefieldFamily",
    
       "parents": [
          { "familyName": "Wakefield", "givenName": "Robin" },
          { "familyName": "Miller", "givenName": "Ben" }
       ],
    
       "children": [
          {
             "familyName": "Merriam",
             "givenName": "Jesse",
             "gender": "female",
             "grade": 6,
    
             "pets": [
                { "givenName": "Charlie Brown", "type": "Dog" },
                { "givenName": "Tiger", "type": "Cat" },
                { "givenName": "Princess", "type": "Cat" }
             ]
          },
    
          {
             "familyName": "Miller",
             "givenName": "Lisa",
             "gender": "female",
             "grade": 3,
    
             "pets": [
                { "givenName": "Jake", "type": "Snake" }
             ]
          }
       ],
    
       "location": { "state": "NY", "county": "Manhattan", "city": "NY" },
       "isRegistered": false
    }
    

    Let’s take a look at a simple example in which a comparison operator is used in WHERE clause.

    Comparison Operator

    In this query, in WHERE clause, the (WHERE f.id = “WakefieldFamily”) condition is specified, and it will retrieve the document whose id is equal to WakefieldFamily.

    SELECT *
    FROM f
    WHERE f.id = "WakefieldFamily"
    

    When the above query is executed, it will return the complete JSON document for WakefieldFamily as shown in the following output.

    [
       {
          "id": "WakefieldFamily",
          "parents": [
             {
                "familyName": "Wakefield",
                "givenName": "Robin"
             },
    
             {
                "familyName": "Miller",
                "givenName": "Ben"
             }
          ],
    
          "children": [
             {
                "familyName": "Merriam",
                "givenName": "Jesse",
                "gender": "female",
                "grade": 6,
    
                "pets": [
                   {
                      "givenName": "Charlie Brown",
                      "type": "Dog"
                   },
    
                   {
                      "givenName": "Tiger",
                      "type": "Cat"
                   },
    
                   {
                      "givenName": "Princess",
                      "type": "Cat"
                   }
                ]
    
             },
    
             {
                "familyName": "Miller",
                "givenName": "Lisa",
                "gender": "female",
                "grade": 3,
    
                "pets": [
                   {
                      "givenName": "Jake",
                      "type": "Snake"
                   }
                ]
             }
          ],
    
          "location": {
             "state": "NY",
             "county": "Manhattan",
             "city": "NY"
          },
    
          "isRegistered": false,
          "_rid": "Ic8LAJFujgECAAAAAAAAAA==",
          "_ts": 1450541623,
          "_self": "dbs/Ic8LAA==/colls/Ic8LAJFujgE=/docs/Ic8LAJFujgECAAAAAAAAAA==/",
          "_etag": ""00000500-0000-0000-0000-567582370000"",
          "_attachments": "attachments/"
       }
    ]
    

    Let’s take a look at another example in which the query will retrieve the children data whose grade is greater than 5.

    SELECT *
    FROM Families.children[0] c
    WHERE (c.grade > 5)
    

    When the above query is executed, it will retrieve the following sub document as shown in the output.

    [
       {
          "familyName": "Merriam",
          "givenName": "Jesse",
          "gender": "female",
          "grade": 6,
    
          "pets": [
             {
                "givenName": "Charlie Brown",
                "type": "Dog"
             },
    
             {
                "givenName": "Tiger",
                "type": "Cat"
             },
    
             {
                "givenName": "Princess",
                "type": "Cat"
             }
          ]
       }
    ]
    

    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 SQL – Order By Clause nhận dự án làm có lương

    DocumentDB SQL – Order By Clause



    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.

    We will consider the same documents as in the previous examples.

    Following is the AndersenFamily document.

    {
       "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
    }
    

    Following is the SmithFamily document.

    {
       "id": "SmithFamily",
    
       "parents": [
          { "familyName": "Smith", "givenName": "James" },
          { "familyName": "Curtis", "givenName": "Helen" }
       ],
    
       "children": [
          {
             "givenName": "Michelle",
             "gender": "female",
             "grade": 1
          },
    
          {
             "givenName": "John",
             "gender": "male",
             "grade": 7,
    
             "pets": [
                { "givenName": "Tweetie", "type": "Bird" }
             ]
          }
       ],
    
       "location": {
          "state": "NY",
          "county": "Queens",
          "city": "Forest Hills"
       },
    
       "isRegistered": true
    }
    

    Following is the WakefieldFamily document.

    {
       "id": "WakefieldFamily",
    
       "parents": [
          { "familyName": "Wakefield", "givenName": "Robin" },
          { "familyName": "Miller", "givenName": "Ben" }
       ],
    
       "children": [
          {
             "familyName": "Merriam",
             "givenName": "Jesse",
             "gender": "female",
             "grade": 6,
    
             "pets": [
                { "givenName": "Charlie Brown", "type": "Dog" },
                { "givenName": "Tiger", "type": "Cat" },
                { "givenName": "Princess", "type": "Cat" }
             ]
          },
    
          {
             "familyName": "Miller",
             "givenName": "Lisa",
             "gender": "female",
             "grade": 3,
    
             "pets": [
                { "givenName": "Jake", "type": "Snake" }
             ]
          }
       ],
    
       "location": { "state": "NY", "county": "Manhattan", "city": "NY" },
       "isRegistered": false
    }
    

    Let’s take a look at a simple example.

    Order By Clause

    Following is the query which contains the ORDER BY keyword.

    SELECT  f.id, f.children[0].givenName,f.children[0].grade
    FROM Families f
    ORDER BY f.children[0].grade
    

    When the above query is executed, it produces the following output.

    [
       {
          "id": "SmithFamily",
          "givenName": "Michelle",
          "grade": 1
       },
    
       {
          "id": "AndersenFamily",
          "grade": 5
       },
    
       {
          "id": "WakefieldFamily",
          "givenName": "Jesse",
          "grade": 6
       }
    ]
    

    Let’s consider another simple example.

    Order By Clauses

    Following is the query which contains the ORDER BY keyword and DESC optional keyword.

    SELECT f.id, f.parents[0].familyName
    FROM Families f
    ORDER BY f.parents[0].familyName DESC
    

    When the above query is executed, it will produce the following output.

    [
       {
          "id": "WakefieldFamily",
          "familyName": "Wakefield"
       },
    
       {
          "id": "SmithFamily",
          "familyName": "Smith"
       },
    
       {
          "id": "AndersenFamily"
       }
    ]
    

    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 SQL – Overview nhận dự án làm có lương

    DocumentDB SQL – Overview



    DocumentDB is Microsoft”s newest NoSQL document database platform that runs on Azure. In this tutorial, we will learn all about querying documents using the special version of SQL supported by DocumentDB.

    NoSQL Document Database

    DocumentDB is Microsoft”s newest NoSQL document database, however, when we say NoSQL document database, what precisely do we mean by NoSQL, and document database?

    • SQL means Structured Query Language which is a traditional query language of relational databases. SQL is often equated with relational databases.

    • It is 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

    Why SQL Syntax?

    This can sound strange at first, but in DocumentDB which is a NoSQL database, we query using SQL. As mentioned above, this is a special version of SQL rooted in JSON and JavaScript semantics.

    • SQL is just a language, but it”s also a very popular language that”s rich and expressive. Thus, it definitely seems like a good idea to use some dialect of SQL rather than come up with a whole new way of expressing queries that we would need to learn if you wanted to get documents out of your database.

    • SQL is designed for relational databases, and DocumentDB is a non-relational document database. DocumentDB team has actually adapted the SQL syntax for the non-relational world of document databases, and this is what is meant by rooting SQL in JSON and JavaScript.

    • The language still reads as familiar SQL, but the semantics are all based on schemafree JSON documents rather than relational tables. In DocumentDB, we will be working with JavaScript data types rather than SQL data types. We will be familiar with SELECT, FROM, WHERE, and so on, but with JavaScript types, which are limited to numbers and strings, objects, arrays, Boolean, and null are far fewer than the wide range of SQL data types.

    • Similarly, expressions are evaluated as JavaScript expressions rather than some form of T-SQL. For example, in a world of denormalized data, we”re not dealing with the rows and columns, but schema-free documents with hierarchal structures that contain nested arrays and objects.

    How does SQL Work?

    The DocumentDB team has answered this question in several innovative ways. Few of them are listed as follows −

    • First, assuming you”ve not changed the default behavior to automatically index every property in a document, you can use dotted notation in your queries to navigate a path to any property no matter how deeply nested it may be within the document.

    • You can also perform an intra-document join in which nested array elements are joined with their parent element within a document in a manner very similar to the way a join is performed between two tables in the relational world.

    • Your queries can return documents from the database as it is, or you can project any custom JSON shape you want based on as much or as little of the document data that you want.

    • SQL in DocumentDB supports many of the common operators including −

      • Arithmetic and bitwise operations

      • AND and OR logic

      • Equality and range comparisons

      • String concatenation

    • The query language also supports a host of built-in functions.


    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 SQL – Value Keyword nhận dự án làm có lương

    DocumentDB SQL – Value Keyword



    When you know you”re only returning a single value, then the VALUE keyword can help produce a leaner result set by avoiding the overhead of creating a full-blown object. The VALUE keyword provides a way to return JSON value.

    Let’s take a look at a simple example.

    Value KeyWord

    Following is the query with VALUE keyword.

    SELECT VALUE "Hello World, this is DocumentDB SQL Tutorial"
    

    When this query is executed, it returns the scalar “Hello World, this is DocumentDB SQL Tutorial”.

    [
       "Hello World, this is DocumentDB SQL Tutorial"
    ]
    

    In another example, let’s consider the three documents from the previous examples.

    Following is the AndersenFamily document.

    {
       "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
    }
    

    Following is the SmithFamily document.

    {
       "id": "SmithFamily",
    
       "parents": [
          { "familyName": "Smith", "givenName": "James" },
          { "familyName": "Curtis", "givenName": "Helen" }
       ],
    
       "children": [
          {
             "givenName": "Michelle",
             "gender": "female",
             "grade": 1
          },
    
          {
             "givenName": "John",
             "gender": "male",
             "grade": 7,
    
             "pets": [
                { "givenName": "Tweetie", "type": "Bird" }
             ]
          }
       ],
    
       "location": {
          "state": "NY",
          "county": "Queens",
          "city": "Forest Hills"
       },
    
       "isRegistered": true
    }
    

    Following is the WakefieldFamily document.

    {
       "id": "WakefieldFamily",
    
       "parents": [
          { "familyName": "Wakefield", "givenName": "Robin" },
          { "familyName": "Miller", "givenName": "Ben" }
       ],
    
       "children": [
          {
             "familyName": "Merriam",
             "givenName": "Jesse",
             "gender": "female",
             "grade": 6,
    
             "pets": [
                { "givenName": "Charlie Brown", "type": "Dog" },
                { "givenName": "Tiger", "type": "Cat" },
                { "givenName": "Princess", "type": "Cat" }
             ]
          },
    
          {
             "familyName": "Miller",
             "givenName": "Lisa",
             "gender": "female",
             "grade": 3,
    
             "pets": [
                { "givenName": "Jake", "type": "Snake" }
             ]
          }
       ],
    
       "location": { "state": "NY", "county": "Manhattan", "city": "NY" },
       "isRegistered": false
    }
    

    Following is the query.

    SELECT VALUE f.location
    FROM Families f
    

    When this query is executed, it return the returns the address without the location label.

    [
       {
          "state": "NY",
          "county": "Manhattan",
          "city": "NY"
       },
    
       {
          "state": "NY",
          "county": "Queens",
          "city": "Forest Hills"
       },
    
       {
          "state": "WA",
          "county": "King",
          "city": "Seattle"
       }
    ]
    

    If we now specify the same query without VALUE Keyword, then it will return the address with location label. Following is the query.

    SELECT f.location
    FROM Families f
    

    When this query is executed, it produces the following output.

    [
       {
          "location": {
             "state": "NY",
             "county": "Manhattan",
             "city": "NY"
          }
       },
    
       {
          "location": {
             "state": "NY",
             "county": "Queens",
             "city": "Forest Hills"
          }
       },
    
       {
          "location": {
             "state": "WA",
             "county": "King",
             "city": "Seattle"
          }
       }
    ]
    

    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 SQL – Where Clause nhận dự án làm có lương

    DocumentDB SQL – Where Clause



    In this chapter, we will cover the WHERE clause, which is also optional like FROM clause. It is used to specify a condition while fetching the data in the form of JSON documents provided by the source. Any JSON document must evaluate the specified conditions to be “true” to be considered for the result. If the given condition is satisfied, only then it returns specific data in the form of JSON document(s). We can use WHERE clause to filter the records and fetch only necessary records.

    We will consider the same three documents in this example. Following is the AndersenFamily document.

    {
       "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
    }
    

    Following is the SmithFamily document.

    {
       "id": "SmithFamily",
    
       "parents": [
          { "familyName": "Smith", "givenName": "James" },
          { "familyName": "Curtis", "givenName": "Helen" }
       ],
    
       "children": [
          {
             "givenName": "Michelle",
             "gender": "female",
             "grade": 1
          },
    
          {
             "givenName": "John",
             "gender": "male",
             "grade": 7,
    
             "pets": [
                { "givenName": "Tweetie", "type": "Bird" }
             ]
          }
       ],
    
       "location": {
          "state": "NY",
          "county": "Queens",
          "city": "Forest Hills"
       },
    
       "isRegistered": true
    }
    

    Following is the WakefieldFamily document.

    {
       "id": "WakefieldFamily",
    
       "parents": [
          { "familyName": "Wakefield", "givenName": "Robin" },
          { "familyName": "Miller", "givenName": "Ben" }
       ],
    
       "children": [
          {
             "familyName": "Merriam",
             "givenName": "Jesse",
             "gender": "female",
             "grade": 6,
    
             "pets": [
                { "givenName": "Charlie Brown", "type": "Dog" },
                { "givenName": "Tiger", "type": "Cat" },
                { "givenName": "Princess", "type": "Cat" }
             ]
          },
    
          {
             "familyName": "Miller",
             "givenName": "Lisa",
             "gender": "female",
             "grade": 3,
    
             "pets": [
                { "givenName": "Jake", "type": "Snake" }
             ]
          }
       ],
    
       "location": { "state": "NY", "county": "Manhattan", "city": "NY" },
       "isRegistered": false
    }
    

    Let’s take a look at a simple example in which WHERE clause is used.

    WHERE Clause

    In this query, in WHERE clause, the (WHERE f.id = “WakefieldFamily”) condition is specified.

    SELECT *
    FROM f
    WHERE f.id = "WakefieldFamily"
    

    When the above query is executed, it will return the complete JSON document for WakefieldFamily as shown in the following output.

    [
       {
          "id": "WakefieldFamily",
    
          "parents": [
             {
                "familyName": "Wakefield",
                "givenName": "Robin"
             },
    
             {
                "familyName": "Miller",
                "givenName": "Ben"
             }
          ],
    
          "children": [
             {
                "familyName": "Merriam",
                "givenName": "Jesse",
                "gender": "female",
                "grade": 6,
    
                "pets": [
                   {
                      "givenName": "Charlie Brown",
                      "type": "Dog"
                   },
    
                   {
                      "givenName": "Tiger",
                      "type": "Cat"
                   },
    
                   {
                      "givenName": "Princess",
                      "type": "Cat"
                   }
                ]
             },
    
             {
                "familyName": "Miller",
                "givenName": "Lisa",
                "gender": "female",
                "grade": 3,
    
                "pets": [
                   {
                      "givenName": "Jake",
                      "type": "Snake"
                   }
                ]
    
             }
          ],
    
          "location": {
             "state": "NY",
             "county": "Manhattan",
             "city": "NY"
          },
    
          "isRegistered": false,
          "_rid": "Ic8LAJFujgECAAAAAAAAAA==",
          "_ts": 1450541623,
          "_self": "dbs/Ic8LAA==/colls/Ic8LAJFujgE=/docs/Ic8LAJFujgECAAAAAAAAAA==/",
          "_etag": ""00000500-0000-0000-0000-567582370000"",
          "_attachments": "attachments/"
       }
    ]
    

    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