Documentdb 简明教程

DocumentDB - Quick Guide

DocumentDB - Introduction

在本章中,我们将简要讨论有关 NoSQL 和文档数据库的主要概念。我们还将对 DocumentDB 进行快速概述。

NoSQL Document Database

DocumentDB 是 Microsoft 最新型的 NoSQL 文档数据库,因此当你谈论 NoSQL 文档数据库时,我们确切地指的是什么,是 NoSQL 还是文档数据库?

  1. SQL 表示结构化查询语言,这是关系数据库的传统查询语言。SQL 通常与关系数据库相等。

  2. 将 NoSQL 数据库视为非关系数据库确实更有帮助,因此 NoSQL 真正指的是非关系。

有不同类型的 NoSQL 数据库,包括键值存储,例如:

  1. Azure Table Storage.

  2. Column-based stores like Cassandra.

  3. Graph databases like NEO4.

  4. 文档数据库,例如 MongoDB 和 Azure DocumentDB。

Azure DocumentDB

Microsoft 于 2015 年 4 月 8 日正式推出了 Azure DocumentDB,它肯定可以被描述为一个典型的 NoSQL 文档数据库。它具有大规模可扩展性,并且适用于无模式的 JSON 文档。

  1. DocumentDB 是一款真正的无模式 NoSQL 文档数据库服务,专为现代移动和 Web 应用程序而设计。

  2. 它还提供了始终快速地读取和写入、模式灵活性以及轻松按需向上或向下扩展数据库的能力。

  3. 它不假定或不需要为其编制索引的 JSON 文档的任何模式。

  4. DocumentDB 在将文档添加到数据库中后立即自动编制文档中每个属性的索引。

  5. DocumentDB 支持使用 SQL 语言进行复杂即席查询,每个文档在创建时可立即进行查询,而且你可以在文档层级结构中的任何位置搜索任何属性。

DocumentDB – Pricing

DocumentDB 是基于一个数据库账户中所包含的集合数计费的。每个账户可以有一个或多个数据库,并且每个数据库可以有几乎不受限制的集合数,尽管最初的默认配额为 100。可以通过联系 Azure 支持来取消此配额。

  1. 集合不仅是一个规模单位,而且还是一个成本单位,所以使用 DocumentDB 时,您需要为每个集合付费,每个集合的存储容量高达 10 GB。

  2. 至少,您需要一个 S1 集合来存储数据库中的文档,每月费用约为 25 美元,费用会从您的 Azure 订阅中扣除。

  3. 数据库随着增长而超出 10 GB 后,您需要购买另一个集合来容纳附加数据。

  4. 每个 S1 集合每秒提供 250 个请求单位,如果这还不够,则可以将集合扩展到 S2,每月约 50 美元可获得每秒 1000 个请求单位。

  5. 您还可以一直升级到 S3,每月支付约 100 美元。

DocumentDB - Advantages

DocumentDB 脱颖而出,具有非常独特的功能。Azure DocumentDB 提供了以下关键功能和优势。

Schema Free

在关系数据库中,每个表都具有一个架构,用于定义每个表中的每行必须遵循的列和数据类型。

相反,文档数据库没有定义架构,并且每个文档的结构可以不同。

SQL Syntax

DocumentDB 能够使用 SQL 语言进行复杂的临时查询,并且每份文档在创建后都可以立即进行查询。您可以在文档层次结构中的任何位置对任何属性进行搜索。

Tunable Consistency

它提供了一些详细且定义良好的一致性级别,这使您能够在一致性、可用性和延迟之间进行合理的权衡。

您可以从四个定义明确的一致性级别中进行选择,以在一致性和性能之间实现最佳权衡。对于查询和读取操作,DocumentDB 提供四个不同的级别 −

  1. Strong

  2. Bounded-staleness

  3. Session

  4. Eventual

Elastic Scale

可伸缩性是 NoSQL 的关键,而 DocumentDB 则提供了此功能。DocumentDB 已经证明了它的可伸缩性。

  1. Office OneNote 和 Xbox 等主要服务已由 DocumentDB 支持,其中包含几十兆字节的 JSON 文档、超过一百万活跃用户,并以 99.95% 的可用性始终如一地运行。

  2. 随着应用程序的增长,你可以通过创建更多单元弹性扩展 DocumentDB 以获得可预测的性能。

Fully Managed

DocumentDB 以在 Azure 上运行的服务形式提供,作为一个完全管理的基于云的平台。

  1. 你只需安装或管理操作即可。

  2. 没有服务器、电缆,无需处理操作系统或更新,无需设定复制品。

  3. Microsoft 完成所有这些工作并让服务一直运行。

  4. 在几分钟内,你就可以使用浏览器和 Azure 订阅开始使用 DocumentDB。

DocumentDB - Environment Setup

Microsoft 提供了 Visual Studio 的免费版本,其中还包含 SQL Server,可以从 https://www.visualstudio.com 下载。

Installation

Step 1 - 下载完成后,运行安装程序。将显示以下对话框。

installer

Step 2 - 单击“安装”按钮,安装过程将开始。

installation process

Step 3 - 安装过程成功完成后,您将看到以下对话框。

restart now

Step 4 - 关闭此对话框并在需要时重新启动计算机。

Step 5 - 现在从开始菜单打开 Visual studio,将打开下面的对话框。第一次仅准备需要一些时间。

visual studio

完成后,您将看到 Visual Studio 的主窗口。

main window of visual studio

Step 6 - 让我们从“文件→新建→项目”创建一个新项目。

create new project

Step 7 - 选择控制台应用程序,在“名称”字段中输入 DocumentDBDemo,然后单击“确定”按钮。

Step 8 - 在解决方案资源管理器中,右键单击您的项目。

right click on project

Step 9 - 选择“管理 NuGet 程序包”,这将在 Visual Studio 中打开以下窗口并在“联机搜索”输入框中搜索 DocumentDB 客户端库。

select manage nuget

Step 10 - 通过单击“安装”按钮安装最新版本。

license acceptance

Step 11 - 单击“我接受”。一旦安装完成,您将在输出窗口中看到消息。

start application

你现在可以开始你的应用程序。

DocumentDB - Create Account

若要使用 Microsoft Azure DocumentDB,你必须创建一个 DocumentDB 帐户。在本章中,我们将使用 Azure 门户创建一个 DocumentDB 帐户。

Step 1 − 如果已拥有 Azure 订阅,请登录到在线 https://portal.azure.com ,否则你需要先登录。

你将看到主仪表板。它完全可定制,因此你可以按任何需要的方式排列这些磁贴、调整它们的大小、增加和移除经常使用或不再使用的项目的磁贴。

dashboard

Step 2 − 选择页面左上角的“新建”选项。

new option

Step 3 − 现在选择数据 + 存储 > Azure DocumentDB 选项,你将看到以下新建 DocumentDB 帐户部分。

azure documentdb

我们需要想出一个全局唯一名称(ID),该名称与 .documents.azure.com 结合,是可公开寻址的 DocumentDB 帐户的端点。我们可以使用此端点访问通过该帐户创建的所有数据库。

Step 4 − 我们将其命名为 azuredocdbdemo,然后单击资源组 → new_resource。

resource group

Step 5 − 选择位置,即希望在哪个 Microsoft 数据中心托管此帐户。选择位置并选择你的区域。

select location

Step 6 − 选中固定到仪表板复选框,然后继续单击创建按钮。

create button

你可以看到磁贴已添加到仪表板,并且它让我们知道该帐户正在创建。实际上,为新帐户设置可能需要几分钟,同时 DocumentDB 分配端点、配置副本并执行其他后台工作。

完成后,你将看到仪表板。

account dashboard

Step 7 − 现在单击创建的 DocumentDB 帐户,你将看到一个详细的屏幕,如下所示。

created documentdb

DocumentDB - Connect Account

在你开始对 DocumentDB 编程时,第一步是连接。因此,要连接到你的 DocumentDB 帐户,你需要两样东西;

  1. Endpoint

  2. Authorization Key

Endpoint

端点是你的 DocumentDB 帐户的 URL,它是通过将你的 DocumentDB 帐户名与 .documents.azure.com 结合来构建的。我们进入仪表板。

endpoint

现在,单击创建的 DocumentDB 帐户。你将看到详细信息,如下所示。

click created documentdb

当你选择“密钥”选项时,它将显示更多信息,如下所示。你还会看到你的 DocumentDB 帐户的 URL,你可以用它作为你的端点。

keys

Authorization Key

授权密钥包含你的凭证,并且有两种类型的密钥。主密钥允许访问帐户内的所有资源,而资源令牌允许受限访问特定资源。

Master Keys

  1. 没有任何事情是主密钥不能做的。如果你想要,你可以使用主密钥摧毁你的整个数据库。

  2. 因此,你一定不想共享或将主密钥分配给客户端环境。作为额外的安全措施,最好经常对其进行更改。

  3. 实际上,每个数据库帐户都有两个主密钥,即主密钥和次密钥,如上图所示。

Resource Tokens

  1. 你还可以使用资源令牌,而不是使用主密钥。

  2. 基于资源令牌的连接只能访问令牌指定的资源,而不能访问其他资源。

  3. 资源令牌基于用户权限,因此首先创建一名或多名用户,并且这些用户在数据库级别进行定义。

  4. 你为每个用户创建一项或多项权限,这基于你希望允许每个用户访问的资源。

  5. 每个权限都会生成一个资源令牌,该令牌允许仅读或完全访问某个资源,而该资源可以是数据库中的任何用户资源。

让我们进入在第 3 章中创建的控制台应用程序。

Step 1 − 在 Program.cs 文件中添加以下引用。

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Newtonsoft.Json;

Step 2 − 现在添加端点 URL 和授权密钥。在此示例中,我们将使用主密钥作为授权密钥。

请注意,在你的情况下,端点 URL 和授权密钥都应有所不同。

private const string EndpointUrl = "https://azuredocdbdemo.documents.azure.com:443/";
private const string AuthorizationKey =
   "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";

Step 3 − 在称为 CreateDocumentClient 的异步任务中新建一个 DocumentClient 的实例,并实例化新的 DocumentClient。

Step 4 − 从你的 Main 方法调用异步任务。

以下是迄今为止完整的 Program.cs 文件。

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
         var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);
      }

   }
}

在本章中,我们学习了如何连接到 DocumentDB 帐户和新建一个 DocumentClient 类的实例。

DocumentDB - Create Database

在本章中,我们将学习如何新建一个数据库。要使用 Microsoft Azure DocumentDB,你必须有一个 DocumentDB 帐户、一个数据库、一个集合和文档。我们已经有了 DocumentDB 帐户,现在我们有两种选择来创建数据库 −

  1. Microsoft Azure Portal or

  2. .Net SDK

Create a Database for DocumentDB using the Microsoft Azure Portal

若要使用门户创建数据库,以下为步骤。

Step 1 − 登录到 Azure 门户,你将看到仪表板。

login

Step 2 − 现在单击已创建的 DocumentDB 帐户,你将看到详细信息,如下图所示。

create database

Step 3 − 选择“添加数据库”选项并提供数据库 ID。

add database

Step 4 - 单击“确定”。

database added

您会看到添加了数据库。目前,尚未添加任何集合,但稍后我们可以添加将用于存储 JSON 文档的容器集合。请注意,它同时具有 ID 和资源 ID。

Create a Database for DocumentDB Using .Net SDK

如需使用 .Net SDK 创建数据库,请执行以下步骤。

Step 1 − 从上一章中在 Visual Studio 中打开控制台应用程序。

Step 2 − 创建新的数据库对象来创建新数据库。如需创建新数据库,我们只需分配 Id 属性,我们将其设置为 CreateDatabase 任务中的“mynewdb”。

private async static Task CreateDatabase(DocumentClient client) {
   Console.WriteLine();
   Console.WriteLine("******** Create Database *******");

   var databaseDefinition = new Database { Id = "mynewdb" };
   var result = await client.CreateDatabaseAsync(databaseDefinition);
   var database = result.Resource;

   Console.WriteLine(" Database Id: {0}; Rid: {1}", database.Id, database.ResourceId);
   Console.WriteLine("******** Database Created *******");
}

Step 3 − 现在将此 databaseDefinition 传递给 CreateDatabaseAsync,然后以资源属性的形式获取结果。所有创建对象的方法都返回一个描述已创建项(在本例中为数据库)的资源属性。

从资源属性中获取新的数据库对象,并将其与 DocumentDB 分配给它的资源 ID 一起显示在控制台上。

Step 4 − 现在,在实例化 DocumentClient 后,从 CreateDocumentClient 任务调用 CreateDatabase 任务。

using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
   await CreateDatabase(client);
}

以下是迄今为止完整的 Program.cs 文件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Newtonsoft.Json;

namespace DocumentDBDemo {

   class Program {
      private const string EndpointUrl = "https://azuredocdbdemo.documents.azure.com:443/";

      private const string AuthorizationKey = "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/
         StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";

      static void Main(string[] args) {
         try {
            CreateDocumentClient().Wait();
         } catch (Exception e) {
            Exception baseException = e.GetBaseException();
            Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
         }
         Console.ReadKey();
      }

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

      private async static Task CreateDatabase(DocumentClient client) {
         Console.WriteLine();
         Console.WriteLine("******** Create Database *******");

         var databaseDefinition = new Database { Id = "mynewdb" };
         var result = await client.CreateDatabaseAsync(databaseDefinition);
         var database = result.Resource;

         Console.WriteLine(" Database Id: {0}; Rid: {1}", database.Id, database.ResourceId);
         Console.WriteLine("******** Database Created *******");
      }

   }
}

当编译并执行上述代码时,您会收到以下输出,其中包含数据库和资源 ID。

******** Create Database *******
 Database Id: mynewdb; Rid: ltpJAA==
******** Database Created *******

DocumentDB - List Databases

到目前为止,我们在 DocumentDB 帐户中创建了两个数据库,第一个是使用 Azure 门户创建的,而第二个是使用 .Net SDK 创建的。现在,您可以使用 Azure 门户查看这些数据库。

转到 Azure 门户中的 DocumentDB 帐户,您现在会看到两个数据库。

two databases

您还可以使用 .Net SDK 从代码中查看或列出数据库。以下为相关步骤。

Step 1 − 发出没有参数的数据库查询,该查询会返回完整的列表,但您也可以传入一个查询以查找特定的数据库或特定数据库。

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);
}

您会看到,有一堆用于查找集合、文档、用户和其他资源的 CreateQuery 方法。这些方法实际上并不执行查询,它们只是定义查询并返回可迭代对象。

实际上执行查询、迭代结果并将它们作为列表返回的是对 ToList() 的调用。

Step 2 − 在实例化 DocumentClient 之后,从 CreateDocumentClient 任务调用 GetDatabases 方法。

Step 3 − 您还需要对 CreateDatabase 任务进行注释或更改数据库 ID,否则您会收到一个错误消息,指出数据库已存在。

using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
   //await CreateDatabase(client);
   GetDatabases(client);
}

以下是迄今为止完整的 Program.cs 文件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Newtonsoft.Json;

namespace DocumentDBDemo {

   class Program {
      private const string EndpointUrl = "https://azuredocdbdemo.documents.azure.com:443/";

      private const string AuthorizationKey = "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/
         StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";

      static void Main(string[] args) {
         try {
            CreateDocumentClient().Wait();
         } catch (Exception e) {
            Exception baseException = e.GetBaseException();
            Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
         }
         Console.ReadKey();
      }

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

      private async static Task CreateDatabase(DocumentClient client) {
         Console.WriteLine();
         Console.WriteLine("******** Create Database *******");

         var databaseDefinition = new Database { Id = "mynewdb" };
         var result = await client.CreateDatabaseAsync(databaseDefinition);
         var database = result.Resource;

         Console.WriteLine(" Database Id: {0}; Rid: {1}", database.Id, database.ResourceId);
         Console.WriteLine("******** Database Created *******");
      }

      private static void GetDatabases(DocumentClient client) {
         Console.WriteLine();
         Console.WriteLine();
         Console.WriteLine("******** Get Databases List ********");

         var databases = client.CreateDatabaseQuery().ToList();

         foreach (var database in databases) {
            Console.WriteLine(" Database Id: {0}; Rid: {1}",
               database.Id, database.ResourceId);
         }

         Console.WriteLine();
         Console.WriteLine("Total databases: {0}", databases.Count);
      }

   }
}

当编译并执行上述代码时,您会收到以下输出,其中包含两个数据库的数据库和资源 ID。最后,您还将看到数据库的总数。

******** Get Databases List ********
 Database Id: myfirstdb; Rid: Ic8LAA==
 Database Id: mynewdb; Rid: ltpJAA==
Total databases: 2

DocumentDB - Drop Databases

您可以通过门户或代码(使用 .Net SDK)删除数据库。在这里,我们将按部就班地讨论如何在 DocumentDB 中删除数据库。

Step 1 − 在 Azure 门户上转到 DocumentDB 帐户。为了演示,我添加了另外两个数据库,如下图所示。

drop databases

Step 2 − 若要删除任何数据库,您需要单击该数据库。我们选择 tempdb,您将看到以下页面,选择“删除数据库”选项。

delete database

Step 3 − 它将显示确认信息,现在单击“是”按钮。

confirmation message

您将看到 tempdb 不再出现在仪表板中。

tempdb deleted

您还可以使用 .Net SDK 从代码中删除数据库。以下是要执行的步骤。

Step 1 − 让我们通过指定我们想要删除的数据库的 ID 来删除该数据库,但是我们需要它的 SelfLink。

Step 2 − 我们像之前一样调用 CreateDatabaseQuery,但这次我们实际上提供了一个查询,只返回 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 − 这一次,我们可以调用 AsEnumerable 而不是 ToList(),因为我们实际上不需要列表对象。预期仅一个结果,调用 AsEnumerable 就足够了,这样我们可以使用 First() 获得查询返回的第一个数据库对象。这是 tempdb1 的数据库对象,它具有 SelfLink,我们可以使用 SelfLink 调用 DeleteDatabaseAsync 来删除该数据库。

Step 4 − 您还需要在 DocumentClient 实例化后从 CreateDocumentClient 任务调用 DeleteDatabase 任务。

Step 5 − 若要查看删除指定数据库后的数据库列表,我们再次调用 GetDatabases 方法。

using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
   //await CreateDatabase(client);

   GetDatabases(client);
   await DeleteDatabase(client);
   GetDatabases(client);
}

以下是迄今为止完整的 Program.cs 文件。

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);
      }

   }
}

编译并执行上述代码后,您将收到以下输出,其中包含三个数据库的数据库和资源 ID 以及数据库总数。

******** 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

删除数据库后,您还将在最后看到 DocumentDB 帐户中只剩下两个数据库。

DocumentDB - Create Collection

在本章中,我们将了解如何创建集合。它类似于创建数据库。您可以从门户或使用 .Net SDK 从代码中创建集合。

Step 1 − 转到 Azure 门户上的主仪表板。

create collection

Step 2 − 从数据库列表中选择 myfirstdb。

myfirstdb

Step 3 − 单击“添加集合”选项并为集合指定 ID。为不同的选项选择定价层级。

add collection

Step 4 − 让我们选择 S1 标准,然后单击选择 → 确定按钮。

s1 standard

正如您所看到的,MyCollection 已添加到 myfirstdb 中。

您还可以使用 .Net SDK 从代码中创建集合。让我们了解一下从代码中添加集合的以下步骤。

Step 1 −在 Visual Studio 中打开控制台应用程序。

Step 2 −要创建一个集合,首先通过 CreateDocumentClient 任务中的 ID 检索 myfirstdb 数据库。

private static async Task CreateDocumentClient() {

   // Create a new instance of the DocumentClient
   using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
      database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
         'myfirstdb'").AsEnumerable().First();

      await CreateCollection(client, "MyCollection1");
      await CreateCollection(client, "MyCollection2", "S2");
   }
}

以下是 CreateCollection 任务的实现。

private async static Task CreateCollection(DocumentClient client, string collectionId,
   string offerType = "S1") {

   Console.WriteLine();
   Console.WriteLine("**** Create Collection {0} in {1} ****", collectionId, database.Id);

   var collectionDefinition = new DocumentCollection { Id = collectionId };
   var options = new RequestOptions { OfferType = offerType };
   var result = await client.CreateDocumentCollectionAsync(database.SelfLink,
      collectionDefinition, options);
   var collection = result.Resource;

   Console.WriteLine("Created new collection");
   ViewCollection(collection);
}

我们创建了一个新的 DocumentCollection 对象,该对象使用 CreateDocumentCollectionAsync 方法的新 Id 定义新集合,该方法还接受我们在这里用来设置新集合性能层(我们称为 offerType)的选项参数。

这默认为 S1,并且由于我们没有为 MyCollection1 传入 offerType,所以这将是一个 S1 集合,而对于 MyCollection2,我们已经传递了 S2,这使其成为 S2 如上所示。

以下是 ViewCollection 方法的实现。

private static void ViewCollection(DocumentCollection collection) {
   Console.WriteLine("Collection ID: {0} ", collection.Id);
   Console.WriteLine("Resource ID: {0} ", collection.ResourceId);
   Console.WriteLine("Self Link: {0} ", collection.SelfLink);
   Console.WriteLine("Documents Link: {0} ", collection.DocumentsLink);
   Console.WriteLine("UDFs Link: {0} ", collection.UserDefinedFunctionsLink);
   Console.WriteLine(" StoredProcs Link: {0} ", collection.StoredProceduresLink);
   Console.WriteLine("Triggers Link: {0} ", collection.TriggersLink);
   Console.WriteLine("Timestamp: {0} ", collection.Timestamp);
}

以下是程序的完整实现。collections 中的 cs 文件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;

using Newtonsoft.Json;

namespace DocumentDBDemo {

   class Program {

      private const string EndpointUrl = "https://azuredocdbdemo.documents.azure.com:443/";

      private const string AuthorizationKey = "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/
         StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";

      private static Database database;

      static void Main(string[] args) {
         try {
            CreateDocumentClient().Wait();
         } catch (Exception e) {
            Exception baseException = e.GetBaseException();
            Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
         }
         Console.ReadKey();
      }

      private static async Task CreateDocumentClient() {
         // Create a new instance of the DocumentClient
         using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
            database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
               'myfirstdb'").AsEnumerable().First();
            await CreateCollection(client, "MyCollection1");
            await CreateCollection(client, "MyCollection2", "S2");

            //await CreateDatabase(client);
            //GetDatabases(client);
            //await DeleteDatabase(client);
            //GetDatabases(client);
         }
      }

      private async static Task CreateCollection(DocumentClient client,
         string collectionId, string offerType = "S1") {

         Console.WriteLine();
         Console.WriteLine("**** Create Collection {0} in {1} ****", collectionId,
            database.Id);

         var collectionDefinition = new DocumentCollection { Id = collectionId };
         var options = new RequestOptions { OfferType = offerType };
         var result = await

			client.CreateDocumentCollectionAsync(database.SelfLink,
            collectionDefinition, options);
         var collection = result.Resource;

         Console.WriteLine("Created new collection");
         ViewCollection(collection);
      }

      private static void ViewCollection(DocumentCollection collection) {
         Console.WriteLine("Collection ID: {0} ", collection.Id);
         Console.WriteLine("Resource ID: {0} ", collection.ResourceId);
         Console.WriteLine("Self Link: {0} ", collection.SelfLink);
         Console.WriteLine("Documents Link: {0} ", collection.DocumentsLink);
         Console.WriteLine("UDFs Link: {0} ", collection.UserDefinedFunctionsLink);
         Console.WriteLine("StoredProcs Link: {0} ", collection.StoredProceduresLink);
         Console.WriteLine("Triggers Link: {0} ", collection.TriggersLink);
         Console.WriteLine("Timestamp: {0} ", collection.Timestamp);
      }

   }
}

编译和执行上述代码后,您将收到包含所有与集合相关信息在内的以下输出。

**** Create Collection MyCollection1 in myfirstdb ****
Created new collection
   Collection ID: MyCollection1
      Resource ID: Ic8LAPPvnAA=
         Self Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/
   Documents Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/docs/
         UDFs Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/udfs/
   StoredProcs Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/sprocs/
      Triggers Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/triggers/
         Timestamp: 12/10/2015 4:55:36 PM

**** Create Collection MyCollection2 in myfirstdb ****
Created new collection
   Collection ID: MyCollection2
      Resource ID: Ic8LAKGHDwE=
         Self Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/
   Documents Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/docs/
         UDFs Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/udfs/
   StoredProcs Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/sprocs/
      Triggers Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/triggers/
         Timestamp: 12/10/2015 4:55:38 PM

DocumentDB - Delete Collection

要删除集合或集合,您可以使用 .Net SDK 从门户和代码中执行此操作。

Step 1 −转到 Azure 门户上的 DocumentDB 帐户。为了演示的目的,我添加了另外两个集合,如以下屏幕截图所示。

delete collection

Step 2 −要删除任何集合,您需要单击该集合。选择 TempCollection1。 您将看到以下页面,选择“删除集合”选项。

select collection

Step 3 −它将显示确认消息。现在点击“是”按钮。

delete collection message

您将看到仪表板上不再有 TempCollection1。

collection deleted

您还可以使用 .Net SDK 从代码中删除集合。为此,请执行以下步骤。

Step 1 −让我们通过指定要删除的集合的 ID 来删除该集合。

这是按 ID 查询以获取删除资源所需的 selfLinks 的常用模式。

private async static Task DeleteCollection(DocumentClient client, string collectionId) {
   Console.WriteLine();
   Console.WriteLine("**** Delete Collection {0} in {1} ****", collectionId, database.Id);

   var query = new SqlQuerySpec {
      QueryText = "SELECT * FROM c WHERE c.id = @id",
         Parameters = new SqlParameterCollection {
         new SqlParameter {
            Name = "@id", Value = collectionId
         }
      }
   };

   DocumentCollection collection = client.CreateDocumentCollectionQuery(database.SelfLink,
      query).AsEnumerable().First();

   await client.DeleteDocumentCollectionAsync(collection.SelfLink);
   Console.WriteLine("Deleted collection {0} from database {1}", collectionId,
      database.Id);
}

在这里,我们将看到构造参数化查询的首选方式。我们没有对 collectionId 进行硬编码,因此此方法可用于删除任何集合。我们通过 Id 查询特定集合,其中 Id 参数在此 SqlParameterCollection 中定义,该 SqlParameterCollection 已分配给该 SqlQuerySpec 的参数属性。

然后,SDK 会继续构建最终的查询字符串,以便 DocumentDB 将 collectionId 嵌入在其中。

Step 2 −运行查询,然后使用其 SelfLink 从 CreateDocumentClient 任务中删除该集合。

private static async Task CreateDocumentClient() {
   // Create a new instance of the DocumentClient

   using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
      database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
         'myfirstdb'").AsEnumerable().First();
      await DeleteCollection(client, "TempCollection");
   }
}

以下是 Program.cs 文件的完整实现。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;

using Newtonsoft.Json;

namespace DocumentDBDemo {

   class Program {

      private const string EndpointUrl = "https://azuredocdbdemo.documents.azure.com:443/";

      private const string AuthorizationKey = "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/
         StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";

      private static Database database;

      static void Main(string[] args) {
         try {
            CreateDocumentClient().Wait();
         } catch (Exception e) {
            Exception baseException = e.GetBaseException();
            Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
         }
         Console.ReadKey();
      }

      private static async Task CreateDocumentClient() {
         // Create a new instance of the DocumentClient
         using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
            database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
               'myfirstdb'").AsEnumerable().First();
            await DeleteCollection(client, "TempCollection");

            //await CreateCollection(client, "MyCollection1");
            //await CreateCollection(client, "MyCollection2", "S2");
            ////await CreateDatabase(client);
            //GetDatabases(client);
            //await DeleteDatabase(client);
            //GetDatabases(client);
         }
      }

      private async static Task CreateCollection(DocumentClient client,
         string collectionId, string offerType = "S1") {

         Console.WriteLine();
         Console.WriteLine("**** Create Collection {0} in {1} ****", collectionId,
            database.Id);

         var collectionDefinition = new DocumentCollection { Id = collectionId };
         var options = new RequestOptions { OfferType = offerType };
         var result = await client.CreateDocumentCollectionAsync(database.SelfLink,
            collectionDefinition, options);

         var collection = result.Resource;

         Console.WriteLine("Created new collection");
         ViewCollection(collection);
      }

      private static void ViewCollection(DocumentCollection collection) {
         Console.WriteLine("Collection ID: {0} ", collection.Id);
         Console.WriteLine("Resource ID: {0} ", collection.ResourceId);
         Console.WriteLine("Self Link: {0} ", collection.SelfLink);
         Console.WriteLine("Documents Link: {0} ", collection.DocumentsLink);
         Console.WriteLine("UDFs Link: {0} ", collection.UserDefinedFunctionsLink);
         Console.WriteLine("StoredProcs Link: {0} ", collection.StoredProceduresLink);
         Console.WriteLine("Triggers Link: {0} ", collection.TriggersLink);
         Console.WriteLine("Timestamp: {0} ", collection.Timestamp);
      }

      private async static Task DeleteCollection(DocumentClient client,
         string collectionId) {

         Console.WriteLine();
         Console.WriteLine("**** Delete Collection {0} in {1} ****", collectionId,
            database.Id);

         var query = new SqlQuerySpec {
            QueryText = "SELECT * FROM c WHERE c.id = @id", Parameters = new
               SqlParameterCollection {
               new SqlParameter {
                  Name = "@id", Value = collectionId
               }
            }
         };

         DocumentCollection collection = client.CreateDocumentCollectionQuery
            (database.SelfLink, query).AsEnumerable().First();

         await client.DeleteDocumentCollectionAsync(collection.SelfLink);
         Console.WriteLine("Deleted collection {0} from database {1}", collectionId,
            database.Id);
      }

   }
}

当上文代码被编译和执行时,您将收到如下输出。

**** Delete Collection TempCollection in myfirstdb ****
Deleted collection TempCollection from database myfirstdb

DocumentDB - Insert Document

在本教程中,我们将着手处理集合中的实际文档。您可以使用 Azure 门户或 .Net SDK 创建文档。

Creating Documents with the Azure Portal

让我们看一下将文档添加到您的集合的以下步骤。

Step 1 − 在 myfirstdb 中添加新的 S1 定价层的 Families 集合。

insert document

Step 2 − 选择 Families 集合,然后单击“创建文档”选项,打开“新建文档”面板。

families collection

这是一个简单的文本编辑器,它允许您为新文档输入任何 JSON。

simple text editor

Step 3 − 这是原始数据输入,让我们输入我们的第一个文档。

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

当您输入上述文档时,您会看到以下屏幕。

document

请注意,我们已为文档提供了一个 id。id 值总是必需的,而且在同一个集合中的所有其他文档中必须唯一。如果您忽略这一点,那么 DocumentDB 会使用 GUID 或全局唯一标识符自动为您生成一个。

id 始终是一个字符串,它不能是数字、日期、布尔值或其他对象,也不能超过 255 个字符。

还要注意文档的分层结构,该结构具有一些顶级属性,例如必需的 id 以及 lastName 和 isRegistered,但它还具有嵌套属性。

例如,parents 属性作为 JSON 数组提供,由方括号表示。我们还为 children 提供了另一个数组,尽管在该示例此数组中只有一个子项。

Step 4 − 单击“保存”按钮以保存文档,我们已创建了我们的第一个文档。

正如您所看到的,我们的 JSON 已经应用了漂亮的格式,该格式将每个属性拆分为单独的行,并用一个空格缩进以传达每个属性的嵌套级别。

save document

该门户包括一个文档浏览器,所以现在让我们使用它来检索我们刚刚创建的文档。

retrieve document

Step 5 − 选择一个数据库和数据库中任何集合,查看该集合中的文档。我们当前只有一个名为 myfirstdb 的数据库,其中包含一个名为 Families 的集合,两者在此处下拉菜单中都已预先选择。

choose database

默认情况下,文档浏览器会显示集合中未经过滤的文档列表,但您还可以通过 ID 搜索任何特定文档,或根据部分 ID 的通配符搜索搜索多个文档。

到目前为止,我们的集合中只有一个文档,我们在以下屏幕上看到了它的 ID,AndersonFamily。

Step 6 − 单击 ID 以查看文档。

click on id

Creating Documents with the .NET SDK

众所周知,文档只是另一种类型的资源,并且您已经熟悉如何使用 SDK 处理资源。

  1. 文档与其他资源之间最大的区别在于当然它们是无架构的。

  2. 因此有很多选项。当然,您只能处理 JSON 对象图甚至 JSON 文本的原始字符串,但您还可以使用动态对象,这些动态对象允许您在运行时绑定到属性,而无需在编译时定义类。

  3. 您还可以处理真正的 C# 对象或实体(如其称谓),这可能是您的业务域类。

让我们在使用 .Net SDK 时开始创建文档。以下是步骤。

Step 1 − 实例化 DocumentClient,然后我们将查询 myfirstdb 数据库,再查询 MyCollection 集合,我们将此存储在私有变量集合中,以便可以在整个类中访问它。

private static async Task CreateDocumentClient() {
   // Create a new instance of the DocumentClient

   using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
      database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
         'myfirstdb'").AsEnumerable().First();

      collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
         "SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First();

      await CreateDocuments(client);
   }
}

Step 2 − 在 CreateDocuments 任务中创建一些文档。

private async static Task CreateDocuments(DocumentClient client) {
   Console.WriteLine();
   Console.WriteLine("**** Create Documents ****");
   Console.WriteLine();

   dynamic document1Definition = new {
      name = "New Customer 1", address = new {
         addressType = "Main Office",
         addressLine1 = "123 Main Street",
         location = new {
            city = "Brooklyn", stateProvinceName = "New York"
         }, postalCode = "11229", countryRegionName = "United States"
      },
   };

   Document document1 = await CreateDocument(client, document1Definition);
   Console.WriteLine("Created document {0} from dynamic object", document1.Id);
   Console.WriteLine();
}

第一个文档将由此动态对象生成。这可能看起来像 JSON,但当然不是。这是 C# 代码,我们正在创建一个真正的 .NET 对象,但没有类定义。相反,属性是从对象初始化方式中推断出来的。

请注意,我们没有为此文档提供 Id 属性。

现在,让我们看一下 CreateDocument。它看起来像我们为创建数据库和集合而看到的相同模式。

private async static Task<Document> CreateDocument(DocumentClient client,
   object documentObject) {

   var result = await client.CreateDocumentAsync(collection.SelfLink, documentObject);
   var document = result.Resource;

   Console.WriteLine("Created new document: {0}\r\n{1}", document.Id, document);
   return result;
}

Step 3 − 这一次,我们调用 CreateDocumentAsync 来指定要向其中添加文档的集合的 SelfLink。我们返回一个具有 resource 属性的响应,在这种情况下,它表示具有系统生成属性的新文档。

Document 对象是 SDK 中的已定义类,它继承自 resource,因此它具有所有常见的 resource 属性,但也包括定义无架构文档本身的动态属性。

private async static Task CreateDocuments(DocumentClient client) {
   Console.WriteLine();
   Console.WriteLine("**** Create Documents ****");
   Console.WriteLine();

   dynamic document1Definition = new {
      name = "New Customer 1", address = new {
         addressType = "Main Office",
         addressLine1 = "123 Main Street",
         location = new {
            city = "Brooklyn", stateProvinceName = "New York"
         }, postalCode = "11229", countryRegionName = "United States"
      },
   };

   Document document1 = await CreateDocument(client, document1Definition);
   Console.WriteLine("Created document {0} from dynamic object", document1.Id);
   Console.WriteLine();
}

当以上代码编译并执行时,您将收到以下输出。

**** Create Documents ****
Created new document: 34e9873a-94c8-4720-9146-d63fb7840fad {
   "name": "New Customer 1",

   "address": {
      "addressType": "Main Office",
      "addressLine1": "123 Main Street",
      "location": {
         "city": "Brooklyn", "stateProvinceName": "New York"
      },
      "postalCode": "11229", "countryRegionName": "United States"
   },

   "id": "34e9873a-94c8-4720-9146-d63fb7840fad",
   "_rid": "Ic8LAMEUVgACAAAAAAAAAA==",
   "_ts": 1449812756,
   "_self": "dbs/Ic8LAA==/colls/Ic8LAMEUVgA=/docs/Ic8LAMEUVgACAAAAAAAAAA==/",
   "_etag": "\"00001000-0000-0000-0000-566a63140000\"",
   "_attachments": "attachments/"
}
Created document 34e9873a-94c8-4720-9146-d63fb7840fad from dynamic object

如您所见,我们没有提供 Id,但是 DocumentDB 为我们生成了新文档的 Id。

DocumentDB - Query Document

在 DocumentDB 中,我们实际上使用 SQL 查询文档,因此本章全是关于在 DocumentDB 中使用特殊 SQL 语法的查询。虽然如果您正在进行 .NET 开发,也可以使用可生成适当 SQL 的 LINQ 提供程序。

Querying Document using Portal

Azure 门户具有查询浏览器,可让您针对 DocumentDB 数据库运行任何 SQL 查询。

我们将使用查询浏览器来演示查询语言的许多不同功能和特性,从最简单的查询开始。

Step 1 − 在数据库边栏中,单击打开查询浏览器边栏。

query explorer blade

记住查询运行在集合的范围内,因此 Query Explorer 允许您在此下拉列表中选择集合。

run query

Step 2 − 选择之前使用门户创建的 Families 集合。

Query Explorer 使用这个简单的查询 SELECT * FROM c 打开,它只从集合中检索所有文档。

Step 3 − 通过点击“运行查询”按钮执行此查询。然后您会看到完整的文档在“结果”面板中被检索出来。

document in result blade

Querying Document using .Net SDK

以下是使用 .Net SDK 运行一些文档查询的步骤。

在这个例子中,我们要查询我们刚刚添加的新创建的文档。

Step 1 − 调用 CreateDocumentQuery,将集合通过其 SelfLink 和查询文本传递给要针对其运行查询的集合。

private async static Task QueryDocumentsWithPaging(DocumentClient client) {
   Console.WriteLine();
   Console.WriteLine("**** Query Documents (paged results) ****");
   Console.WriteLine();
   Console.WriteLine("Quering for all documents");

   var sql = "SELECT * FROM c";
   var query = client.CreateDocumentQuery(collection.SelfLink, sql).AsDocumentQuery();

   while (query.HasMoreResults) {
      var documents = await query.ExecuteNextAsync();

      foreach (var document in documents) {
         Console.WriteLine(" Id: {0}; Name: {1};", document.id, document.name);
      }
   }

   Console.WriteLine();
}

此查询也返回整个集合中的所有文档,但是我们没像之前那样对 CreateDocumentQuery 调用 .ToList,这将发出尽可能多的请求,以便在一行代码中提取所有结果。

Step 2 − 相反,调用 AsDocumentQuery,此方法返回一个具有 HasMoreResults 属性的查询对象。

Step 3 − 如果 HasMoreResults 为真,那么调用 ExecuteNextAsync 获取下一个块,然后转储该块中的所有内容。

Step 4 − 如果你愿意,你可以使用 LINQ 而不用 SQL 进行查询。这里我们在 q 中定义了一个 LINQ 查询,但是它在我们在其上运行 .ToList 之前不会执行。

private static void QueryDocumentsWithLinq(DocumentClient client) {
   Console.WriteLine();
   Console.WriteLine("**** Query Documents (LINQ) ****");
   Console.WriteLine();
   Console.WriteLine("Quering for US customers (LINQ)");

   var q =
      from d in client.CreateDocumentQuery<Customer>(collection.DocumentsLink)
      where d.Address.CountryRegionName == " United States"
      select new {
         Id = d.Id,
         Name = d.Name,
         City = d.Address.Location.City
      };

   var documents = q.ToList();
   Console.WriteLine("Found {0} UK customers", documents.Count);

   foreach (var document in documents) {
      var d = document as dynamic;
      Console.WriteLine(" Id: {0}; Name: {1}; City: {2}", d.Id, d.Name, d.City);
   }

   Console.WriteLine();
}

SDK 将把我们的 LINQ 查询转换为 DocumentDB 的 SQL 语法,根据我们的 LINQ 语法生成 SELECT 和 WHERE 子句

Step 5 − 现在从 CreateDocumentClient 任务调用上述查询。

private static async Task CreateDocumentClient() {
   // Create a new instance of the DocumentClient

   using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
      database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
         'myfirstdb'").AsEnumerable().First();

      collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
         "SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First();

      //await CreateDocuments(client);
      await QueryDocumentsWithPaging(client);
      QueryDocumentsWithLinq(client);
   }

}

执行上述代码后,您将收到以下输出。

**** Query Documents (paged results) ****
Quering for all documents
 Id: 7e9ad4fa-c432-4d1a-b120-58fd7113609f; Name: New Customer 1;
 Id: 34e9873a-94c8-4720-9146-d63fb7840fad; Name: New Customer 1;

**** Query Documents (LINQ) ****
Quering for US customers (LINQ)
Found 2 UK customers
 Id: 7e9ad4fa-c432-4d1a-b120-58fd7113609f; Name: New Customer 1; City: Brooklyn
 Id: 34e9873a-94c8-4720-9146-d63fb7840fad; Name: New Customer 1; City: Brooklyn

DocumentDB - Update Document

在本章中,我们将学习如何更新文档。使用 Azure 门户,您可以通过在文档浏览器中打开文档,并且更新编辑器中的内容(比如一个文本文件)来轻松更新文档。

update document

点击“保存”按钮。现在,如果您需要使用 .Net SDK 更改文档,您可以直接替换它。您无需删除并重新创建它,这不仅繁琐乏味,而且还会更改资源标识符,这是您在修改文档时不希望的。以下是使用 .Net SDK 更新文档的步骤。

让我们看一下以下 ReplaceDocuments 任务,其中我们查询 isNew 属性为真文档,但是我们什么也得不到,因为没有这样的文档。因此,让我们修改早期添加的文档,那些名称以 New Customer 开头的文档。

Step 1 − 向这些文档添加 isNew 属性,并将其值设置为真。

private async static Task ReplaceDocuments(DocumentClient client) {

   Console.WriteLine();
   Console.WriteLine(">>> Replace Documents <<<");
   Console.WriteLine();
   Console.WriteLine("Quering for documents with 'isNew' flag");

   var sql = "SELECT * FROM c WHERE c.isNew = true";
   var documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList();

   Console.WriteLine("Documents with 'isNew' flag: {0} ", documents.Count);
   Console.WriteLine();
   Console.WriteLine("Quering for documents to be updated");

   sql = "SELECT * FROM c WHERE STARTSWITH(c.name, 'New Customer') = true";
   documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList();
   Console.WriteLine("Found {0} documents to be updated", documents.Count);

   foreach (var document in documents) {
      document.isNew = true;
      var result = await client.ReplaceDocumentAsync(document._self, document);
      var updatedDocument = result.Resource;
      Console.WriteLine("Updated document 'isNew' flag: {0}", updatedDocument.isNew);
   }

   Console.WriteLine();
   Console.WriteLine("Quering for documents with 'isNew' flag");

   sql = "SELECT * FROM c WHERE c.isNew = true";
   documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList();
   Console.WriteLine("Documents with 'isNew' flag: {0}: ", documents.Count);
   Console.WriteLine();
}

Step 2 − 使用相同的 STARTSWITH 查询获取要更新的文档,它给了我们文档,我们以动态对象形式获取它们。

Step 3 − 附加 isNew 属性,并为每个文档将其设置为真。

Step 4 − 调用ReplaceDocumentAsync,传递文档的SelfLink,以及更新后的文档。

现在只需证明它有效,查询isNew等于true的文档。让我们从CreateDocumentClient任务中调用上述查询。

private static async Task CreateDocumentClient() {
   // Create a new instance of the DocumentClient

   using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
      database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
         'myfirstdb'").AsEnumerable().First();

      collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
         "SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First();

      //await CreateDocuments(client);
      //QueryDocumentsWithSql(client);
      //await QueryDocumentsWithPaging(client);
      //QueryDocumentsWithLinq(client);
      await ReplaceDocuments(client);
   }

}

当上文代码被编译和执行时,您将收到如下输出。

**** Replace Documents ****
Quering for documents with 'isNew' flag
Documents with 'isNew' flag: 0
Quering for documents to be updated
Found 2 documents to be updated
Updated document ‘isNew’ flag: True
Updated document ‘isNew’ flag: True
Quering for documents with 'isNew' flag
Documents with 'isNew' flag: 2

DocumentDB - Delete Document

在本章中,我们将学习如何从您的 DocumentDB 帐户中删除文档。使用 Azure 门户后,您可以通过在 Document Explorer 中打开文档并单击“删除”选项,轻松删除任何文档。

delete document
delete document dialog

它会显示确认消息。现在,按下“是”按钮,您将看到 DocumentDB 帐户中不再有该文档。

现在,当您想使用 .Net SDK 删除文档时。

Step 1 − 它与我们之前看到过的模式相同,我们将在其中首先查询以获得每个新文档的 SelfLinks。我们此处不使用 SELECT *,它将返回文档的全部内容,而这是我们不需要的。

Step 2 − 相反,我们仅将 SelfLinks 选择到列表中,然后我们每次仅对一个 SelfLink 调用 DeleteDocumentAsync,以从集合中删除文档。

private async static Task DeleteDocuments(DocumentClient client) {
   Console.WriteLine();
   Console.WriteLine(">>> Delete Documents <<<");
   Console.WriteLine();
   Console.WriteLine("Quering for documents to be deleted");

   var sql =
      "SELECT VALUE c._self FROM c WHERE STARTSWITH(c.name, 'New Customer') = true";

   var documentLinks =
      client.CreateDocumentQuery<string>(collection.SelfLink, sql).ToList();

   Console.WriteLine("Found {0} documents to be deleted", documentLinks.Count);

   foreach (var documentLink in documentLinks) {
      await client.DeleteDocumentAsync(documentLink);
   }

   Console.WriteLine("Deleted {0} new customer documents", documentLinks.Count);
   Console.WriteLine();
}

Step 3 − 现在让我们从 CreateDocumentClient 任务调用上述的 DeleteDocuments。

private static async Task CreateDocumentClient() {
   // Create a new instance of the DocumentClient
   using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
      database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
         'myfirstdb'").AsEnumerable().First();

      collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
         "SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First();

      await DeleteDocuments(client);
   }
}

执行上述代码后,您将收到以下输出。

***** Delete Documents *****
Quering for documents to be deleted
Found 2 documents to be deleted
Deleted 2 new customer documents

DocumentDB - Data Modeling

虽然无模式数据库(如DocumentDB)让您非常容易地接受对数据模型的更改,但您仍然应该花一些时间考虑您的数据。

  1. 你有许多选择。当然,您只能使用JSON对象图或甚至JSON文本的原始字符串,但您还可以使用动态对象,它允许您在运行时绑定到属性,而无需在编译时定义类。

  2. 您还可以处理真正的 C# 对象或实体(如其称谓),这可能是您的业务域类。

Relationships

让我们看一下文档的层次结构。它有一些顶级属性,例如必需的id,以及lastName和isRegistered,但它还具有嵌套属性。

{
   "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
}
  1. 例如,parents属性以方括号表示的JSON数组形式提供。

  2. 我们还有另一个用于子级的数组,尽管在这个示例中数组中只含有一个子级。因此这就是您在文档中对一对多关系建模的方法。

  3. 您只需使用数组,其中数组中的每个元素都可能是一个简单值或另一个复杂对象,甚至是另一个数组。

  4. 因此一个家庭可以有多个父母和多个孩子,如果你查看孩子对象,它们有一个pets属性,它本身是一个嵌套数组,用于表示孩子和宠物之间的一对多关系。

  5. 对于Location属性,我们将三个相关属性(state、county和city)组合到一个对象中。

  6. 以这种方式嵌入对象而不是嵌入对象数组类似于在关系数据库中的两个单独表的两个行之间建立一对一关系。

Embedding Data

当您开始在文档存储中(如DocumentDB)对数据建模时,请尝试将您的实体视为JSON中表示的自包含文档。当使用关系数据库时,我们总是对数据进行规范化。

  1. 对数据进行规范化通常涉及采用一个实体(如客户),并将其分解为不同的数据片段,如联系方式和地址。

  2. 要读取一个客户以及其所有联系方式和地址,您需要使用JOIN在运行时有效地聚合您的数据。

现在让我们来看看如何在文档数据库中将相同的数据建模为自包含的实体。

{
   "id": "1",
   "firstName": "Mark",
   "lastName": "Upston",

   "addresses": [
      {
         "line1": "232 Main Street",
         "line2": "Unit 1",
         "city": "Brooklyn",
         "state": "NY",
         "zip": 11229
      }
   ],

   "contactDetails": [
      {"email": "mark.upston@xyz.com"},
      {"phone": "+1 356 545-86455", "extension": 5555}
   ]
}

正如您所见,我们已经非规范化了客户记录,其中客户的所有信息都嵌入到一个JSON文档中。

在NoSQL中,我们有免费模式,因此您也可以以不同的格式添加联系方式和地址。在NoSQL中,您可以通过一次读取操作从数据库中检索客户记录。同样,更新记录也只是一次写入操作。

以下是用.Net SDK创建文档的步骤。

Step 1 − 实例化DocumentClient。然后我们将查询myfirstdb数据库,也查询MyCollection集合,我们将该集合存储在这个private变量集合中,以便整个类中都能访问它。

private static async Task CreateDocumentClient() {
   // Create a new instance of the DocumentClient

   using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
      database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
         'myfirstdb'").AsEnumerable().First();

      collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
         "SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First();

      await CreateDocuments(client);
   }

}

Step 2 − 在 CreateDocuments 任务中创建一些文档。

private async static Task CreateDocuments(DocumentClient client) {
   Console.WriteLine();
   Console.WriteLine("**** Create Documents ****");
   Console.WriteLine();

   dynamic document1Definition = new {
      name = "New Customer 1", address = new {
         addressType = "Main Office",
         addressLine1 = "123 Main Street",
         location = new {
            city = "Brooklyn", stateProvinceName = "New York"
         },
         postalCode = "11229", countryRegionName = "United States"
      },
   };

   Document document1 = await CreateDocument(client, document1Definition);
   Console.WriteLine("Created document {0} from dynamic object", document1.Id);
   Console.WriteLine();
}

第一个文档将从这个动态对象生成。这看起来像 JSON,但当然不是。这是 C# 代码,我们正在创建真实的 .NET 对象,但没有类定义。而是根据对象初始化的方式推断属性。您还可能注意到,我们未为该文档提供 Id 属性。

Step 3 - 现在让我们看看 CreateDocument,它看起来与我们看到的用于创建数据库和集合的模式相同。

private async static Task<Document> CreateDocument(DocumentClient client,
   object documentObject) {
   var result = await client.CreateDocumentAsync(collection.SelfLink, documentObject);

   var document = result.Resource;
   Console.WriteLine("Created new document: {0}\r\n{1}", document.Id, document);

   return result;
}

Step 4 - 这次,我们调用 CreateDocumentAsync,指定要向其中添加文档的集合的 SelfLink。我们收到响应,该响应具有 resource 属性,在此情况下,它表示具有其系统生成属性的新文档。

在以下 CreateDocuments 任务中,我们创建了三个文档。

  1. 在第一个文档中,Document 对象是 SDK 中定义的类,它继承自 resource,因此具有所有公共资源属性,但它还包括定义无模式文档本身的动态属性。

private async static Task CreateDocuments(DocumentClient client) {
   Console.WriteLine();
   Console.WriteLine("**** Create Documents ****");
   Console.WriteLine();

   dynamic document1Definition = new {
      name = "New Customer 1", address = new {
         addressType = "Main Office",
         addressLine1 = "123 Main Street",
         location = new {
            city = "Brooklyn", stateProvinceName = "New York"
         },
         postalCode = "11229",
         countryRegionName = "United States"
      },
   };

   Document document1 = await CreateDocument(client, document1Definition);
   Console.WriteLine("Created document {0} from dynamic object", document1.Id);
   Console.WriteLine();

   var document2Definition = @" {
      ""name"": ""New Customer 2"",

      ""address"": {
         ""addressType"": ""Main Office"",
         ""addressLine1"": ""123 Main Street"",
         ""location"": {
            ""city"": ""Brooklyn"", ""stateProvinceName"": ""New York""
         },
         ""postalCode"": ""11229"",
         ""countryRegionName"": ""United States""
      }
   }";

   Document document2 = await CreateDocument(client, document2Definition);
   Console.WriteLine("Created document {0} from JSON string", document2.Id);
   Console.WriteLine();

   var document3Definition = new Customer {
      Name = "New Customer 3",

      Address = new Address {
         AddressType = "Main Office",
         AddressLine1 = "123 Main Street",
         Location = new Location {
            City = "Brooklyn", StateProvinceName = "New York"
         },
         PostalCode = "11229",
         CountryRegionName = "United States"
      },
   };

   Document document3 = await CreateDocument(client, document3Definition);
   Console.WriteLine("Created document {0} from typed object", document3.Id);
   Console.WriteLine();
}
  1. 第二个文档只使用原始 JSON 字符串。现在,我们进入 CreateDocument 的重载,它使用 JavaScriptSerializer 将字符串反序列化为对象,然后将其传递给我们用来创建第一个文档的相同 CreateDocument 方法。

  2. 在第三个文档中,我们使用了应用程序中定义的 C# 对象 Customer。

让我们看看这个客户,它具有一个 Id 和 address 属性,其中 address 是一个嵌套对象,具有自己的属性,包括 location,它还是另一个嵌套对象。

using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DocumentDBDemo {

   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; }
   }

   public class Address {
      [JsonProperty(PropertyName = "addressType")]
      public string AddressType { get; set; }

      [JsonProperty(PropertyName = "addressLine1")]
      public string AddressLine1 { get; set; }

      [JsonProperty(PropertyName = "location")]
      public Location Location { get; set; }

      [JsonProperty(PropertyName = "postalCode")]
      public string PostalCode { get; set; }

      [JsonProperty(PropertyName = "countryRegionName")]
      public string CountryRegionName { get; set; }
   }

   public class Location {
      [JsonProperty(PropertyName = "city")]
      public string City { get; set; }

      [JsonProperty(PropertyName = "stateProvinceName")]
      public string StateProvinceName { get; set; }
   }
}

我们还设置了 JSON 属性属性,因为我们希望在双方面都保持适当的约定。

所以我只需创建我的 New Customer 对象及其嵌套子对象,并再次调用 CreateDocument。尽管我们的客户对象确实有一个 Id 属性,但我们没有为它提供值,因此 DocumentDB 根据 GUID 生成了一个值,就像它对前两个文档所做的那样。

当以上代码编译并执行时,您将收到以下输出。

**** Create Documents ****
Created new document: 575882f0-236c-4c3d-81b9-d27780206b2c
{
  "name": "New Customer 1",
  "address": {
    "addressType": "Main Office",
    "addressLine1": "123 Main Street",
    "location": {
      "city": "Brooklyn",
      "stateProvinceName": "New York"
    },
    "postalCode": "11229",
    "countryRegionName": "United States"
  },
  "id": "575882f0-236c-4c3d-81b9-d27780206b2c",
  "_rid": "kV5oANVXnwDGPgAAAAAAAA==",
  "_ts": 1450037545,
  "_self": "dbs/kV5oAA==/colls/kV5oANVXnwA=/docs/kV5oANVXnwDGPgAAAAAAAA==/",
  "_etag": "\"00006fce-0000-0000-0000-566dd1290000\"",
  "_attachments": "attachments/"
}
Created document 575882f0-236c-4c3d-81b9-d27780206b2c from dynamic object
Created new document: 8d7ad239-2148-4fab-901b-17a85d331056
{
  "name": "New Customer 2",
  "address": {
    "addressType": "Main Office",
    "addressLine1": "123 Main Street",
    "location": {
      "city": "Brooklyn",
      "stateProvinceName": "New York"
    },
    "postalCode": "11229",
    "countryRegionName": "United States"
  },
  "id": "8d7ad239-2148-4fab-901b-17a85d331056",
  "_rid": "kV5oANVXnwDHPgAAAAAAAA==",
  "_ts": 1450037545,
  "_self": "dbs/kV5oAA==/colls/kV5oANVXnwA=/docs/kV5oANVXnwDHPgAAAAAAAA==/",
  "_etag": "\"000070ce-0000-0000-0000-566dd1290000\"",
  "_attachments": "attachments/"
}
Created document 8d7ad239-2148-4fab-901b-17a85d331056 from JSON string
Created new document: 49f399a8-80c9-4844-ac28-cd1dee689968
{
  "id": "49f399a8-80c9-4844-ac28-cd1dee689968",
  "name": "New Customer 3",
  "address": {
    "addressType": "Main Office",
    "addressLine1": "123 Main Street",
    "location": {
      "city": "Brooklyn",
      "stateProvinceName": "New York"
    },
    "postalCode": "11229",
    "countryRegionName": "United States"
  },
  "_rid": "kV5oANVXnwDIPgAAAAAAAA==",
  "_ts": 1450037546,
  "_self": "dbs/kV5oAA==/colls/kV5oANVXnwA=/docs/kV5oANVXnwDIPgAAAAAAAA==/",
  "_etag": "\"000071ce-0000-0000-0000-566dd12a0000\"",
  "_attachments": "attachments/"
}
Created document 49f399a8-80c9-4844-ac28-cd1dee689968 from typed object

DocumentDB - Data Types

JSON 或 JavaScript 对象表示法是一种轻量级的基于文本的开放标准,旨在实现人类可读的数据交换,并且机器也易于解析和生成。JSON 是 DocumentDB 的核心。我们在网络上传输 JSON,我们将 JSON 存储为 JSON,并且我们对 JSON 树进行索引,以便针对完整的 JSON 文档进行查询。

JSON 格式支持以下数据类型 -

S.No.

Type & Description

1

Number JavaScript 中的双精度浮点格式

2

String 带有反斜杠转义的双引号 Unicode

3

Boolean True or false

4

Array 一个有序的值序列

5

Value 它可以是字符串,数字,真或假,null 等。

6

Object 一个无序的键值对集合

7

Whitespace 它可以在任何一对标记之间使用

8

Null Empty

让我们看一个简单的例子 DateTime 类型。为客户类添加出生日期。

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; }
}

我们能用 DateTime 存储、检索以及查询,如下代码所示。

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();
}

当上述代码编译并执行时,并且创建了文档后,您将会看到现已添加出生日期。

**** 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

DocumentDB - Limiting Records

Microsoft 最近添加了许多改善,说明您如何查询 Azure DocumentDB,例如 SQL 语法的 TOP 关键字,它使查询运行更快并消耗更少的资源,增加了查询运算符的限制,并且为 .NET SDK 中的其他 LINQ 运算符添加了支持。

让我们来看一个简单的示例,我们将在其中仅检索前两条记录。如果您有一些记录,并且您想仅检索其中某些记录,那么您可以使用 Top 关键字。在此示例中,我们有许多地震记录。

limiting records

现在我们只想要显示前两条记录

Step 1 - 转到查询浏览器并运行此查询。

SELECT * FROM c
WHERE c.magnitude > 2.5

您将会看到它已检索了 4 条记录,因为我们尚未指定 TOP 关键字。

retrieved records

Step 2 - 现在与相同查询一起使用 TOP 关键字。这里我们指定了 TOP 关键字,而“2”表示我们仅需要两条记录。

SELECT TOP 2 * FROM c
WHERE c.magnitude > 2.5

Step 3 - 现在运行此查询,您将会看到仅检索了两条记录。

two records retrieved

同样地,您可以使用 .Net SDK 的代码中的 TOP 关键字。以下是实现。

private async static Task QueryDocumentsWithPaging(DocumentClient client) {
   Console.WriteLine();
   Console.WriteLine("**** Query Documents (paged results) ****");
   Console.WriteLine();
   Console.WriteLine("Quering for all documents");

   var sql = "SELECT TOP 3 * FROM c";
   var query = client
      .CreateDocumentQuery(collection.SelfLink, sql)
      .AsDocumentQuery();

   while (query.HasMoreResults) {
      var documents = await query.ExecuteNextAsync();

      foreach (var document in documents) {
         Console.WriteLine(" PublicId: {0}; Magnitude: {1};", document.publicid,
            document.magnitude);
      }
   }

   Console.WriteLine();
}

以下是 CreateDocumentClient 任务,在其中实例化了 DocumentClient 和地震数据库。

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 =
         'earthquake'").AsEnumerable().First();

      collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
         "SELECT * FROM c WHERE c.id = 'earthquakedata'").AsEnumerable().First();

      await QueryDocumentsWithPaging(client);
   }
}

当上述代码编译并执行时,您将会看到仅检索了 3 条记录。

**** Query Documents (paged results) ****

Quering for all documents
PublicId: 2015p947400; Magnitude: 2.515176918;
PublicId: 2015p947373; Magnitude: 1.506774108;
PublicId: 2015p947329; Magnitude: 1.593394461;

DocumentDB - Sorting Records

Microsoft Azure DocumentDB 支持使用 JSON 文档中的 SQL 查询文档。您可以使用查询中的 ORDER BY 子句按照数字和字符串对集合中的文档进行排序。该子句可以包含一个可选的 ASC/DESC 参数,以指定必须检索结果的顺序。

让我们来看一下以下示例,在其中我们有一个 JSON 文档。

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

}

以下是按降序对结果进行排序的 SQL 查询。

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

执行上述查询时,您将收到以下输出。

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

DocumentDB - Indexing Records

默认情况下,DocumentDB 会自动索引文档中的每个属性,只要该文档添加到数据库中。但是,您可以进行控制并微调自己的索引策略,这会在不必要索引特定文档和/或属性时减少存储和处理开销。

默认索引策略会告诉 DocumentDB 自动索引每个属性,这适用于许多常见情况。但是,您还可以实现一项定制的策略,它对将索引用哪个以及不使用哪个执行精细控制,并对索引使用其他功能。

DocumentDB 支持以下索引类型:

  1. Hash

  2. Range

Hash

哈希索引支持对相等进行有效查询,换句话说,在搜索文档时,给定属性等于一个精确值,而不是匹配小于、大于或介于一定值范围之内的值。

您可以使用哈希索引执行范围查询,但 DocumentDB 无法使用哈希索引来查找匹配的文档,而需要顺序扫描每个文档以确定它是否应由范围查询选择。

您无法使用仅具有哈希索引的属性上的 ORDER BY 子句对文档进行排序。

Range

DocumentDB 为属性定义了范围索引,您可以有效查询一系列值的文档。它还允许您使用 ORDER BY 根据该属性对查询结果进行排序。

DocumentDB 允许您为任何或所有属性定义哈希和范围索引,这支持相等和范围查询以及 ORDER BY。

Indexing Policy

每个集合都有一个索引策略,决定了在每个文档的每个属性中数字和字符串使用哪类索引。

  1. 您还可以控制是否在将文档添加到集合时自动对其进行索引。

  2. 默认情况下启用自动索引,但您可以在添加文档时覆盖此行为,指示 DocumentDB 不要为该特定文档建立索引。

  3. 您可以禁用自动索引,以便在将文档添加到集合时默认情况下不为其建立索引。同样,您可以在文档级别覆盖此行为,并指示 DocumentDB 在将特定文档添加到集合时对其建立索引。这称为手动索引。

Include / Exclude Indexing

索引策略还可以定义路径或应包含在索引中或排除在索引之外的路径。如果您知道某个文档的某些部分永远不会作为查询条件,而某些部分却会作为查询条件,那么这很有用。

在这些情况下,您可以通过指示 DocumentDB 仅为添加到集合的每个文档的那些特定部分建立索引来减少索引开销。

Automatic Indexing

让我们来看一个自动索引的简单示例。

Step 1 − 首先,我们创建一个名为 autoindexing 的集合,而无需明确提供策略,此集合使用默认索引策略,这意味着启用此集合上的自动索引。

这里我们使用基于 ID 的路由来获得数据库自引用链接,因此我们无需在创建集合之前知道其资源 ID 或查询它。我们可以仅仅使用数据库 ID,即 mydb。

Step 2 − 现在,让我们创建两个文档,姓氏均为 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");
}

第一个文档属于 Mark Upston,已添加到集合中,然后立即根据默认索引策略自动对其建立索引。

但是,当添加第二个 Mark Upston 的文档时,我们已发送带有 IndexingDirective.Exclude 的请求选项,此选项明确指示 DocumentDB 不要为该文档建立索引,尽管有集合的索引策略。

我们最终为两个文档设置了不同类型的查询。

Step 3 − 让我们从 CreateDocumentClient 中调用 AutomaticIndexing 任务。

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

当上文代码被编译和执行时,您将收到如下输出。

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

正如您所见,我们有两个这样的文档,但查询仅返回马克的那个,因为马克的那个未编入索引。如果我们再次查询,不使用 WHERE 子句来检索集合中的所有文档,那么结果集将包含这两个文档,这是因为始终通过没有 WHERE 子句的查询返回未编制索引的文档。

我们还可按其 ID 或自链接检索未编制索引的文档。因此,当我们按其 ID MARK 查询马克的文档时,我们看到 DocumentDB 返回该文档,尽管它未在集合中编制索引。

Manual Indexing

我们来看一个简单的示例,通过覆盖自动索引来进行手动索引。

Step 1 − 首先,我们将创建一个名为 manualindexing 的集合,并通过明确禁用自动索引来覆盖默认策略。这意味着,除非我们提出其他请求,否则添加到此集合的新文档将不会编制索引。

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 − 现在,我们将再次创建与之前相同的两个文档。这一次,由于集合的索引策略,我们不会为马克的文档提供任何特殊请求选项,该文档将不会编制索引。

Step 3 − 现在,当我们添加马克的第二个文档时,我们使用带 IndexingDirective.Include 的 RequestOptions 告诉 DocumentDB 它应该索引此文档,这将覆盖集合中所说的不应该索引的索引策略。

我们最终为两个文档设置了不同类型的查询。

Step 4 − 从 CreateDocumentClient 调用 ManualIndexing 任务。

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

当以上代码编译并执行时,您将收到以下输出。

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

同样,该查询仅返回两个文档中的一个,但这一次,它返回简·多伊,我们明确要求对该文档编制索引。但与之前一样,不使用 WHERE 子句进行查询也会检索集合中的所有文档,包括马克的未编制索引的文档。我们还可以按 ID 查询未编制索引的文档,DocumentDB 会返回该文档,即使未对其编制索引。

DocumentDB - Geospatial Data

Microsoft 添加了 geospatial support ,它允许您在文档中存储位置数据,并对点和多边形之间的距离和相交进行空间计算。

  1. 空间数据描述对象在空间中的位置和形状。

  2. 通常,它可用于表示人的位置、景点或城市或湖泊的边界。

  3. 常见用例通常涉及邻近度查询。例如,“查找离我当前位置最近的所有大学”。

Point 表示空间中的单个位置,它表示确切位置,例如特定大学的街道地址。点在 DocumentDB 中使用其坐标对(经度和纬度)表示。以下是 JSON 点示例。

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

我们来看一个包含大学位置的简单示例。

{
   "id":"case-university",
   "name":"CASE: Center For Advanced Studies In Engineering",
   "city":"Islamabad",

   "location": {
      "type":"Point",
      "coordinates":[ 33.7194136, -73.0964862 ]
   }
}

若要根据位置检索大学名称,您可以使用以下查询。

SELECT c.name FROM c

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

执行以上查询时,您将收到以下输出。

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

Create Document with Geospatial Data in .NET

您可以创建包含地理空间数据的新文档,我们来看一个创建大学文档的简单示例。

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();
}

以下是 UniversityProfile 类的实现。

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; }
}

当上文代码被编译和执行时,您将收到如下输出。

**** 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

DocumentDB - Partitioning

当数据库开始增长到超过 10GB 时,只需创建新集合,然后在越来越多的集合中传播或分区您的数据,即可轻松扩展。

迟早,10GB容量的单个集合将不足以容纳你的数据库。现在10GB听起来可能不算是很大数字,但是请记住,我们正在存储JSON文档,其中只是纯文本,而且即便考虑到索引的存储开销,你也可以在10GB中放入许多纯文本文档。

对于可扩展性而言,存储并不是唯一的问题。在某个集合中可用的最大吞吐量为每秒两千五百个请求单元,你可以通过S3集合获得这个吞吐量。因此,如果你需要更高的吞吐量,那么你还需要通过使用多个集合进行分区来扩展。扩展分区也称为 horizontal partitioning

可以使用许多方法对Azure DocumentDB中的数据分区。以下是最常见策略:

  1. Spillover Partitioning

  2. Range Partitioning

  3. Lookup Partitioning

  4. Hash Partitioning

Spillover Partitioning

溢出分区是最简单的策略,因为它没有分区键。当你对很多事情不确定时,它往往是个不错的开端。你可能不知道你是否需要扩展到单个集合之外,或者你需要添加多少集合,又或者你可能需要多快添加它们。

  1. 溢出分区从单个集合开始,并且没有分区键。

  2. 该集合开始增长,然后增长更多,再增长更多,直到你接近10GB限制。

  3. 当你达到90%的容量时,你溢出到新集合,并开始将它用于新文档。

  4. 一旦数据库扩展到大量集合,你可能希望转向基于分区键的策略。

  5. 执行此操作时,你需要根据你迁移到的任何策略,通过将文档移动到不同集合重新平衡数据。

Range Partitioning

最常见的策略之一是范围分区。使用这种方法,你可以确定文档分区键可能落入的值范围,并将文档定向到与该范围相对应的集合中。

  1. 文档通常使用此策略,你可以创建一个集合来保存落在定义的日期范围内的文档。当你定义足够小的范围时,你可以确信没有集合会超过其10GB限制。例如,可能出现一个场景,其中单个集合可以合理地处理整个月的文档。

  2. 大多数用户查询当前数据的情况也可能发生,该数据可能是本月的或可能是上个月的,但用户很少搜索较旧的数据。因此,你从6月开始使用S3集合,它是你可以购买的最昂贵的集合,并且提供你所能获得的最佳吞吐量。

  3. 在7月,你购买另一个S3集合来存储7月的数据,并且你将6月的数据缩小到一个较便宜的S2集合。然后,在8月,你得到另一个S3集合并缩小7月到S2,并将6月一直缩小到S1。它一个接一个地进行,在这种情况下,你一直保持当前数据可用以获得高吞吐量,并且以较低的吞吐量保持旧数据可用。

  4. 只要查询提供分区键,那么只有需要查询的集合才会被查询,并且不会像溢出分区中那样对数据库中的所有集合进行查询。

Lookup Partitioning

使用查找分区,你可以定义一个分区映射,根据其分区键将文档路由到特定集合。例如,你可以按区域分区。

  1. 将所有美国文档存储在一个集合中,将所有欧洲文档存储在另一个集合中,并将所有其他区域的文档存储在第三个集合中。

  2. 使用此分区映射和查找分区解析器可以根据每个文档中包含的区域属性(即分区键)找出在哪个集合中创建文档以及查询哪些集合。

Hash Partitioning

在哈希分区中,分区根据哈希函数的值分配,从而使你可以在多个分区中均匀地分布请求和数据。

这通常用于对大量不同客户端产生或使用的数据进行分区,并且对于存储用户配置文件、目录项等非常有用。

让我们来看一下使用 .NET SDK 提供的 RangePartitionResolver 对范围分区进行简单分区的示例。

Step 1 − 创建一个新的 DocumentClient,我们将在 CreateCollections 任务中创建两个集合。一个集合将包含用户 ID 以 A 到 M 开头的用户的文档,另一个集合将包含用户 ID 为 N 到 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 − 为数据库注册范围解析器。

Step 3 − 创建一个新的 RangePartitionResolver<string>,即分区键的数据类型。此构造函数接收两个参数,分区键的属性名称以及字典,该字典是分片映射或分区映射,它只是我们为解析器预定义的范围列表和对应集合。

private static void RegisterRangeResolver(DocumentClient client) {

   //Note: \uffff is the largest UTF8 value, so M\ufff includes all strings that start with M.

   var resolver = new RangePartitionResolver<string>(
      "userId", new Dictionary<Range<string>, string>() {
      { new Range<string>("A", "M\uffff"), "dbs/myfirstdb/colls/CollectionAM" },
      { new Range<string>("N", "Z\uffff"), "dbs/myfirstdb/colls/CollectionNZ" },
   });

   client.PartitionResolvers["dbs/myfirstdb"] = resolver;
 }

必须在此处编码尽可能大的 UTF-8 值。否则,第一个范围将不会匹配到任何 M,除了单个 M,同样,第二个范围中的 Z 也是如此。因此,您可以将此编码值视为匹配分区键的通配符。

Step 4 − 在创建解析器后,使用当前的 DocumentClient 为数据库注册它。为此,只需将其赋给 PartitionResolver 的字典属性即可。

我们将针对数据库而不是集合(像您通常所做的那样)创建和查询文档,解析器将使用此映射将请求路由到适当的集合。

现在,让我们创建一些文档。首先,我们将为 userId Kirk 创建一个文档,然后为 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);
}

此处的第一个参数是到数据库的自我链接,而不是特定集合。如果没有分区解析器,这是不可能的,但如果有一个,它只会无缝地工作。

如果 RangePartitionResolver 工作正常,两个文档都将保存到数据库 myfirstdb 中,但我们知道 Kirk 存储在 A 到 M 的集合中,而 Spock 存储在 N 到 Z 的集合中。

让我们在 CreateDocumentClient 任务中调用这些文档,如下面的代码所示。

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);
   }
}

执行上述代码后,您将收到以下输出。

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

正如所见,由于两个文档位于两个不同的集合中,因此这两个文档的自我链接具有不同的资源 ID。

DocumentDB - Data Migration

利用 DocumentDB 数据迁移工具,您可以轻松地将数据迁移到 DocumentDB。DocumentDB 数据迁移工具是一个免费且开源的工具,您可以从 Microsoft 下载中心 https://www.microsoft.com/ 下载该工具。

迁移工具支持许多数据源,其中一些如下所列 −

  1. SQL Server

  2. JSON files

  3. Flat files of Comma-separated Values (CSV)

  4. MongoDB

  5. Azure Table Storage

  6. Amazon DynamoDB

  7. HBase,甚至其他 DocumentDB 数据库

下载 DocumentDB 数据迁移工具后,解压该 zip 文件。

您可以在此文件夹中看到两个可执行文件,如下面的屏幕截图所示。

exe files

首先,有 dt.exe,这是具有命令行界面的控制台版本,然后是 dtui.exe,这是具有图形用户界面的桌面版本。

我们来启动 GUI 版本。

launch gui version

您会看到欢迎页面。单击“下一步”以获取源信息页面。

source information

这是您配置数据源的地方。您可以在下拉菜单中看到受支持的许多选项。

specify source information

当您做出选择时,源信息页面的其余部分将相应更改。

DocumentDB 数据迁移工具可轻松导入数据。我们建议您执行上述示例并使用其他数据文件。

DocumentDB - Access Control

DocumentDB 提供了控制对 DocumentDB 资源的访问的概念。对 DocumentDB 资源的访问由主密钥令牌或资源令牌控制。基于资源令牌的连接只能访问令牌指定的资源,而不能访问其他资源。资源令牌基于用户权限。

  1. 首先,创建一到多个用户,并且这些用户在数据库级别上是经过定义的。

  2. 然后,为每个用户创建一到多个权限,具体取决于希望允许每个用户访问的资源。

  3. 每个权限都会生成一个资源令牌,该令牌允许仅读或完全访问某个资源,而该资源可以是数据库中的任何用户资源。

  4. 用户在数据库级别上进行定义,权限针对每个用户进行定义。

  5. 用户和权限应用于数据库中的所有集合。

我们来看一个简单的示例,在这个示例中,我们将了解如何定义用户和权限,以实现在 DocumentDB 中的细粒度安全。

从一个新的 DocumentClient 开始,查询 myfirstdb 数据库。

private static async Task CreateDocumentClient() {
   // Create a new instance of the DocumentClient
   using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
      database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
         'myfirstdb'").AsEnumerable().First();

      collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
         "SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First();

      var alice = await CreateUser(client, "Alice");
      var tom = await CreateUser(client, "Tom");
   }
}

下面是 CreateUser 的实现。

private async static Task<User> CreateUser(DocumentClient client, string userId) {
   Console.WriteLine();
   Console.WriteLine("**** Create User {0} in {1} ****", userId, database.Id);

   var userDefinition = new User { Id = userId };
   var result = await client.CreateUserAsync(database.SelfLink, userDefinition);
   var user = result.Resource;

   Console.WriteLine("Created new user");
   ViewUser(user);

   return user;
}

Step 1 −创建两个用户 Alice 和 Tom,就像我们创建的任何资源一样。根据所需的 ID 构建一个定义对象,然后调用 create 方法;在该示例中,我们正在调用 CreateUserAsync 以及数据库的 SelfLink 和 userDefinition。我们从新创建的用户对象的 resource 属性中获取返回的结果。

现在查看数据库中的这两个新用户。

private static void ViewUsers(DocumentClient client) {
   Console.WriteLine();
   Console.WriteLine("**** View Users in {0} ****", database.Id);

   var users = client.CreateUserQuery(database.UsersLink).ToList();
   var i = 0;

   foreach (var user in users) {
      i++;
      Console.WriteLine();
      Console.WriteLine("User #{0}", i);
      ViewUser(user);
   }

   Console.WriteLine();
   Console.WriteLine("Total users in database {0}: {1}", database.Id, users.Count);
}

private static void ViewUser(User user) {
   Console.WriteLine("User ID: {0} ", user.Id);
   Console.WriteLine("Resource ID: {0} ", user.ResourceId);
   Console.WriteLine("Self Link: {0} ", user.SelfLink);
   Console.WriteLine("Permissions Link: {0} ", user.PermissionsLink);
   Console.WriteLine("Timestamp: {0} ", user.Timestamp);
}

Step 2 −针对数据库的 UsersLink 调用 CreateUserQuery,以检索所有用户的列表。然后遍历这些用户并查看它们的属性。

现在我们必须首先创建它们。所以假设我们想要允许 Alice 对 MyCollection 集合进行读/写,而 Tom 只可以读取集合中的文档。

await CreatePermission(client, alice, "Alice Collection Access", PermissionMode.All,
   collection);

await CreatePermission(client, tom, "Tom Collection Access", PermissionMode.Read,
   collection);

Step 3 −在一个资源(MyCollection 集合)上创建权限,因此我们需要获得该资源的 SelfLink。

Step 4 −然后为 Alice 创建这个集合的 Permission.All,为 Tom 创建这个集合的 Permission.Read。

以下是 CreatePermission 的实现。

private async static Task CreatePermission(DocumentClient client, User user,
   string permId, PermissionMode permissionMode, string resourceLink) {
   Console.WriteLine();
   Console.WriteLine("**** Create Permission {0} for {1} ****", permId, user.Id);

   var permDefinition = new Permission {
      Id = permId,
      PermissionMode = permissionMode,
      ResourceLink = resourceLink
   };

   var result = await client.CreatePermissionAsync(user.SelfLink, permDefinition);
   var perm = result.Resource;
   Console.WriteLine("Created new permission");
   ViewPermission(perm);
}

正如你预期的那样,我们通过创建一个新的权限的定义对象来实现此操作,其中包括一个 Id 和一个权限模式,它可能是 Permission.All 或 Permission.Read,以及要通过该权限保护的资源的 SelfLink。

@ {s0} − 调用 CreatePermissionAsync 并从结果中的 resource 属性获取已创建的权限。

要查看创建的权限,以下是 ViewPermissions 的实现。

private static void ViewPermissions(DocumentClient client, User user) {
   Console.WriteLine();
   Console.WriteLine("**** View Permissions for {0} ****", user.Id);

   var perms = client.CreatePermissionQuery(user.PermissionsLink).ToList();
   var i = 0;

   foreach (var perm in perms) {
      i++;
      Console.WriteLine();
      Console.WriteLine("Permission #{0}", i);
      ViewPermission(perm);
   }

   Console.WriteLine();
   Console.WriteLine("Total permissions for {0}: {1}", user.Id, perms.Count);
}

private static void ViewPermission(Permission perm) {
   Console.WriteLine("Permission ID: {0} ", perm.Id);
   Console.WriteLine("Resource ID: {0} ", perm.ResourceId);
   Console.WriteLine("Permission Mode: {0} ", perm.PermissionMode);
   Console.WriteLine("Token: {0} ", perm.Token);
   Console.WriteLine("Timestamp: {0} ", perm.Timestamp);
}

这次,它对用户的权限链接进行权限查询,我们只需列出为用户返回的每个权限。

让我们删除 Alice 和 Tom 的权限。

await DeletePermission(client, alice, "Alice Collection Access");
await DeletePermission(client, tom, "Tom Collection Access");

以下是 DeletePermission 的实现。

private async static Task DeletePermission(DocumentClient client, User user,
   string permId) {
   Console.WriteLine();
   Console.WriteLine("**** Delete Permission {0} from {1} ****", permId, user.Id);

   var query = new SqlQuerySpec {
      QueryText = "SELECT * FROM c WHERE c.id = @id",
      Parameters = new SqlParameterCollection {
         new SqlParameter { Name = "@id", Value = permId }
      }
   };

   Permission perm = client.CreatePermissionQuery(user.PermissionsLink, query)
      .AsEnumerable().First();
   await client.DeletePermissionAsync(perm.SelfLink);
   Console.WriteLine("Deleted permission {0} from user {1}", permId, user.Id);
}

@ {s1} − 为了删除权限,按权限 Id 查询以获取 SelfLink,然后使用 SelfLink 删除权限。

接下来,让我们删除用户本人。我们删除这两个用户。

await DeleteUser(client, "Alice");
await DeleteUser(client, "Tom");

以下是 DeleteUser 的实现。

private async static Task DeleteUser(DocumentClient client, string userId) {
   Console.WriteLine();
   Console.WriteLine("**** Delete User {0} in {1} ****", userId, database.Id);

   var query = new SqlQuerySpec {
      QueryText = "SELECT * FROM c WHERE c.id = @id",
      Parameters = new SqlParameterCollection {
         new SqlParameter { Name = "@id", Value = userId }
      }
   };

   User user = client.CreateUserQuery(database.SelfLink, query).AsEnumerable().First();
   await client.DeleteUserAsync(user.SelfLink);
   Console.WriteLine("Deleted user {0} from database {1}", userId, database.Id);
}

@ {s2} − 首先查询以获取她的 SelfLink,然后调用 DeleteUserAsync 以删除她的用户对象。

以下是 CreateDocumentClient 任务的实现,其中我们调用了上述所有任务。

private static async Task CreateDocumentClient() {
   // Create a new instance of the DocumentClient
   using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
      database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
         'myfirstdb'").AsEnumerable().First();

      collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
         "SELECT * FROM c WHERE c.id = 'MyCollection'").AsEnumerable().First();

      ViewUsers(client);

      var alice = await CreateUser(client, "Alice");
      var tom = await CreateUser(client, "Tom");
      ViewUsers(client);

      ViewPermissions(client, alice);
      ViewPermissions(client, tom);

      string collectionLink = client.CreateDocumentCollectionQuery(database.SelfLink,
         "SELECT VALUE c._self FROM c WHERE c.id = 'MyCollection'")
         .AsEnumerable().First().Value;

      await CreatePermission(client, alice, "Alice Collection Access", PermissionMode.All,
         collectionLink);

      await CreatePermission(client, tom, "Tom Collection Access", PermissionMode.Read,
         collectionLink);

      ViewPermissions(client, alice);
      ViewPermissions(client, tom);

      await DeletePermission(client, alice, "Alice Collection Access");
      await DeletePermission(client, tom, "Tom Collection Access");

      await DeleteUser(client, "Alice");
      await DeleteUser(client, "Tom");
   }
}

当以上代码编译并执行时,您将收到以下输出。

**** View Users in myfirstdb ****

Total users in database myfirstdb: 0

**** Create User Alice in myfirstdb ****
Created new user
          User ID: Alice
      Resource ID: kV5oAC56NwA=
        Self Link: dbs/kV5oAA==/users/kV5oAC56NwA=/
 Permissions Link: dbs/kV5oAA==/users/kV5oAC56NwA=/permissions/
        Timestamp: 12/17/2015 5:44:19 PM

**** Create User Tom in myfirstdb ****
Created new user
          User ID: Tom
      Resource ID: kV5oAALxKgA=
        Self Link: dbs/kV5oAA==/users/kV5oAALxKgA=/
 Permissions Link: dbs/kV5oAA==/users/kV5oAALxKgA=/permissions/
        Timestamp: 12/17/2015 5:44:21 PM

**** View Users in myfirstdb ****

User #1
          User ID: Tom
      Resource ID: kV5oAALxKgA=
        Self Link: dbs/kV5oAA==/users/kV5oAALxKgA=/
 Permissions Link: dbs/kV5oAA==/users/kV5oAALxKgA=/permissions/
        Timestamp: 12/17/2015 5:44:21 PM

User #2
          User ID: Alice
      Resource ID: kV5oAC56NwA=
        Self Link: dbs/kV5oAA==/users/kV5oAC56NwA=/
 Permissions Link: dbs/kV5oAA==/users/kV5oAC56NwA=/permissions/
        Timestamp: 12/17/2015 5:44:19 PM

Total users in database myfirstdb: 2

**** View Permissions for Alice ****

Total permissions for Alice: 0

**** View Permissions for Tom ****

Total permissions for Tom: 0

**** Create Permission Alice Collection Access for Alice ****
Created new permission
    Permission ID: Alice Collection Access
      Resource ID: kV5oAC56NwDON1RduEoCAA==
  Permission Mode: All
            Token: type=resource&ver=1&sig=zB6hfvvleC0oGGbq5cc67w==;Zt3Lx
Ol14h8pd6/tyF1h62zbZKk9VwEIATIldw4ZyipQGW951kirueAKdeb3MxzQ7eCvDfvp7Y/ZxFpnip/D G
JYcPyim5cf+dgLvos6fUuiKSFSul7uEKqp5JmJqUCyAvD7w+qt1Qr1PmrJDyAIgbZDBFWGe2VT9FaBH o
PYwrLjRlnH0AxfbrR+T/UpWMSSHtLB8JvNFZNSH8hRjmQupuTSxCTYEC89bZ/pS6fNmNg8=;
        Timestamp: 12/17/2015 5:44:28 PM

**** Create Permission Tom Collection Access for Tom ****
Created new permission
    Permission ID: Tom Collection Access
      Resource ID: kV5oAALxKgCMai3JKWdfAA==
  Permission Mode: Read
            Token: type=resource&ver=1&sig=ieBHKeyi6EY9ZOovDpe76w==;92gwq
V4AxKaCJ2dLS02VnJiig/5AEbPcfo1xvOjR10uK3a3FUMFULgsaK8nzxdz6hLVCIKUj6hvMOTOSN8Lt 7
i30mVqzpzCfe7JO3TYSJEI9D0/5HbMIEgaNJiCu0JPPwsjVecTytiLN56FHPguoQZ7WmUAhVTA0IMP6 p
jQpLDgJ43ZaG4Zv3qWJiO689balD+egwiU2b7RICH4j6R66UVye+GPxq/gjzqbHwx79t54=;
        Timestamp: 12/17/2015 5:44:30 PM

**** View Permissions for Alice ****

Permission #1
    Permission ID: Alice Collection Access
      Resource ID: kV5oAC56NwDON1RduEoCAA==
  Permission Mode: All
            Token: type=resource&ver=1&sig=BSzz/VNe9j4IPJ9M31Mf4Q==;Tcq/B
X50njB1vmANZ/4aHj/3xNkghaqh1OfV95JMi6j4v7fkU+gyWe3mJasO3MJcoop9ixmVnB+RKOhFaSxE l
P37SaGuIIik7GAWS+dcEBWglMefc95L2YkeNuZsjmmW5b+a8ELCUg7N45MKbpzkp5BrmmGVJ7h4Z4pf D
rdmehYLuxSPLkr9ndbOOrD8E3bux6TgXCsgYQscpIlJHSKCKHUHfXWBP2Y1LV2zpJmRjis=;
        Timestamp: 12/17/2015 5:44:28 PM

Total permissions for Alice: 1

**** View Permissions for Tom ****
Permission #1
    Permission ID: Tom Collection Access
      Resource ID: kV5oAALxKgCMai3JKWdfAA==
  Permission Mode: Read
            Token: type=resource&ver=1&sig=NPkWNJp1mAkCASE8KdR6PA==;ur/G2
V+fDamBmzECux000VnF5i28f8WRbPwEPxD1DMpFPqYcu45wlDyzT5A5gBr3/R3qqYkEVn8bU+een6Gl j
L6vXzIwsZfL12u/1hW4mJT2as2PWH3eadry6Q/zRXHAxV8m+YuxSzlZPjBFyJ4Oi30mrTXbBAEafZhA 5
yvbHkpLmQkLCERy40FbIFOzG87ypljREpwWTKC/z8RSrsjITjAlfD/hVDoOyNJwX3HRaz4=;
        Timestamp: 12/17/2015 5:44:30 PM

Total permissions for Tom: 1

**** Delete Permission Alice Collection Access from Alice ****
Deleted permission Alice Collection Access from user Alice

**** Delete Permission Tom Collection Access from Tom ****
Deleted permission Tom Collection Access from user Tom

**** Delete User Alice in myfirstdb ****
Deleted user Alice from database myfirstdb

**** Delete User Tom in myfirstdb ****
Deleted user Tom from database myfirstdb

DocumentDB - Visualize Data

在本章中,我们将学习如何可视化存储在 DocumentDB 中的数据。Microsoft 提供了 Power BI Desktop 工具,它可以将你的数据转换为丰富的可视化效果。它还使你能够从各种数据源中检索数据,合并并转换数据,创建强大的报表和可视化效果,以及将报表发布到 Power BI。

在最新版本的 Power BI Desktop 中,Microsoft 也添加了对 DocumentDB 的支持,现在你可以连接到你的 DocumentDB 帐户。你可以从以下链接下载此工具:@ {s3}

我们来看一个示例,在该示例中,我们将可视化上个章节中导入的地震数据。

@ {s4} − 下载该工具后,启动 Power BI 桌面版。

power bi desktop

@ {s5} − 单击“外部数据”组下“主页”选项卡上的“获取数据”选项,它将显示“获取数据”页面。

get data

@ {s6} − 选择 Microsoft Azure DocumentDB(Beta)选项并单击“连接”按钮。

microsoft azure documentdb

@ {s7} − 输入你要可视化数据的 Azure DocumentDB 帐户、数据库和集合的 URL,然后按确定。

If you are connecting to this endpoint for the first time, you will be prompted for the account key.

account key

Step 5 − Enter the account key (primary key) which is unique for each DocumentDB account available on Azure portal, and then click Connect.

list of records

When the account is successfully connected, it will retrieve the data from specified database. The Preview pane shows a list of Record items, a Document is represented as a Record type in Power BI.

Step 6 − Click ‘Edit’ button which will launch the Query Editor.

edit button

Step 7 − In the Power BI Query Editor, you should see a Document column in the center pane, click on the expander at the right side of the Document column header and select the columns which you want display.

query editor

As you can see that we have latitude and longitude as separate column but we visualize data in latitude, longitude coordinates form.

Step 8 − To do that, click ‘Add Column’ tab.

add column

Step 9 − Select the Add Custom Column which will display the following page.

add custom column

Step 10 − Specify the new column name, let’s say LatLong and also the formula which will combine the latitude and longitude in one column separated by a comma. Following is the formula.

Text.From([latitude])&", "&Text.From([longitude])

Step 11 − Click OK to continue and you will see that the new column is added.

new column added

Step 12 − Go to the Home tab and click ‘Close & Apply’ option.

close and apply

Step 13 − You can create reports by dragging and dropping fields into the Report canvas. You can see on the right, there are two panes − one Visualizations pane and the other is Fields pane.

create reports

Let’s create a map view showing the location of each earthquake.

Step 14 − Drag the map visual type from the Visualizations pane.

Step 15 − Now, drag and drop the LatLong field from the Fields pane to the Location property in Visualizations pane. Then, drag and drop the magnitude field to the Values property.

Step 16 − Drag and drop the depth field to the Color saturation property.

depth field

You will now see the Map visual showing a set of bubbles indicating the location of each earthquake.