阅读 需要大约  5 分钟。

前景:

  Azure Cosmos DB 由 Microsoft 提供,是全球分布式多模型数据库。 通过 Azure Cosmos DB 跨任意数量的 Azure 地理区域弹性且独立地缩放吞吐量和存储。 它通过综合服务级别协议 (SLA) 提供吞吐量、延迟、可用性和一致性保证。Azure Cosmos DB 可以轻松地生成可缩放且响应迅速的全局规模应用程序。

介绍:

  多个数据模型和用于访问及查询数据的常用 API。

  • Azure Cosmos DB 本身所基于的数据模型以 Atom 记录序列 (ARS) 为基础,该模型支持多个数据模型,包括但不限于文档、图形、键-值、表以及列系列数据模型。
  • 多种语言的 SDK 均支持以下数据模型的 API:
    • SQL API:具有丰富 SQL 查询功能的无架构 JSON 数据库引擎。
    • MongoDB API:一种可大规模缩放的服务型 MongoDB,由 Azure Cosmos DB 平台提供支持。 与现有 MongoDB 库、驱动程序、工具和应用程序兼容。
    • Cassandra API:一种可全局分发的服务型 Cassandra,由 Azure Cosmos DB 平台提供支持。 与现有Apache Cassandra 库、驱动程序、工具和应用程序兼容。
    • Gremlin API:一种完全托管的、可横向缩放的图形数据库服务,可以轻松地用于生成和运行特定的应用程序,这些应用程序适用于支持开放式 Gremlin API(基于 Apache TinkerPop 规范:Apache Gremlin)的高度连接数据集。
    • 表 API:一种键值对型数据库服务,可以在不进行任何应用更改的情况下,为现有的 Azure 表存储应用程序提供高级功能(例如,自动索引、低延迟保证、全局分发)

以上是引用Microsoft 官网中文文档,地址:https://docs.microsoft.com/zh-cn/azure/cosmos-db/introduction。

Azure Cosmos DB 是Microsoft 推出的云服务数据库,提供多种API 服务,以下主要讲的是SQL API,以json 形式的文档数据库。

Step 1: 配置环境(使用的是.net core 解决方案)

A > 在appsetting.json 中添加 AccountEndpoint 和 AccountKey

"DocumentDb": {
  "Endpoint": "https://localhost:8081",
  "Key":"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5WF2nQ9nDuVTqoch9b8mGGyPMbIZnqyMsEdsGQy67XIw/Jw=="
}

  

B > 创建Model 类,参数命名需要和appsetting.json 中的命名一样

public class DocumentDbSetting
{
public string Endpoint { get; set; }
public string Key { get; set; }
}

C > 在 startup.cs 中 添加 配置信息

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // 添加的配置
var documentDbSection = Configuration.GetSection("DocumentDb");
services.Configure<DocumentDbSetting>(documentDbSection);
}

D > 创建DocumentDbRepository,获取appsetting.json 中的endpoint 和 key,构造client

private readonly Lazy<IDocumentClient> _client;
public DocumentDbRepository(IOptions<DocumentDbSetting> documentDbSetting)
{
var uri = new Uri(documentDbSetting.Value.Endpoint);
var documentClient = new DocumentClient(uri, documentDbSetting.Value.Key); _client = new Lazy<IDocumentClient>(() => documentClient, true);
}

Step 2: 增删改查的实现

A >  create document(databaseName 指数据库名,collectionName 指的是文档名(相当于表的名称),document 就是存储的一条记录)(以下代码中catch exception 简写了)

public async Task<bool> CreateDocumentAsync<T>(string databaseName, string collectionName, T document) where T : class
{
try
{
await CreateDocumentCollectionAsync(collectionName, databaseName);
var uri = UriFactory.CreateDocumentCollectionUri(databaseName, collectionName); var response = await _client.Value.CreateDocumentAsync(uri, document); bool result = (response != null && (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.OK)); return result;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

  在创建数据时,需要验证database和collection 是否存在,当不存在时,会创建的对应的database和collection。

protected async Task<bool> CreateDatabaseAsync(string databaseName)
{
var db = await _client.Value.CreateDatabaseIfNotExistsAsync(new DocDatabase { Id = databaseName }); return db.StatusCode == HttpStatusCode.Created || db.StatusCode == HttpStatusCode.OK;
} protected async Task<bool> CreateDocumentCollectionAsync(string collectionName, string databaseName)
{
if (string.IsNullOrWhiteSpace(databaseName))
{
throw new ArgumentNullException(nameof(databaseName));
} if (await CreateDatabaseAsync(databaseName))
{
var result = await _client.Value.CreateDocumentCollectionIfNotExistsAsync(
UriFactory.CreateDatabaseUri(databaseName), new DocumentCollection
{
Id = collectionName,
IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 })
}); return result.StatusCode == HttpStatusCode.Created || result.StatusCode == HttpStatusCode.OK;
} return false;
}

B > 修改document有两种方式Upsert 和Replace,Upsert 的特点是 当没有这条数据时,会创建一条,而Replace 会报异常。

Upsert Document

public async Task<bool> UpdateDocumentAsync<T>(string databaseName, string collectionName, T document) where T : class
{
try
{
var uri = UriFactory.CreateDocumentCollectionUri(databaseName, collectionName);
var result = await _client.Value.UpsertDocumentAsync(uri, document); return result.StatusCode == HttpStatusCode.OK || result.StatusCode == HttpStatusCode.Created;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

Replace Document

public async Task<bool> ReplaceDocumentAsync<T>(string databaseName, string collectionName, T document, string id) where T : class
{
try
{
var uri = UriFactory.CreateDocumentUri(databaseName, collectionName, id);
var result = await _client.Value.ReplaceDocumentAsync(uri, document); return result.StatusCode == HttpStatusCode.OK;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

C > Get Document

根据Id获取Document

public async Task<T> GetDocument<T>(string databaseName, string collectionName, string id, FeedOptions feedOptions = null) where T : class
{
try
{
Document document = await _client.Value.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, id)); return (T)(dynamic)document;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

根据条件获取Documents

public async Task<IEnumerable<T>> GetQueryable<T>(string databaseName, string collectionName, Expression<Func<T, bool>> predicate, FeedOptions feedOptions = null) where T : new()
{
var dummy = new T(); IDocumentQuery<T> query = _client.Value.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), feedOptions)
.Where(predicate)
.AsDocumentQuery(); var results = new List<T>(); while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<T>());
} return results;
}

D > Delete Document

public async Task<bool> DeleteDocumentAsync(string databaseName, string collectionName, string documentId)
{
try
{
var documentResponse = await _client.Value.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, documentId));
return documentResponse.StatusCode == HttpStatusCode.NoContent;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}  

本地测试开发使用工具:

Azure Cosmos DB Emulator. 下载地址https://aka.ms/cosmosdb-emulator  ,使用方法

Microsoft Azure Storage Explorer 是存储资源管理器 下载地址https://azure.microsoft.com/en-us/features/storage-explorer/ ,使用方法


在当前的版本中  1. 不支持skip 分页 和group by 分组。 2. 不支持批量操作(插入,修改)等。

 以上只是本人学习笔记分享!有许多不足之处,还在继续添加和更正。本随笔链接:https://www.cnblogs.com/OneManStep/p/10161565.html

Azure Document DB Repository 的实现的更多相关文章

  1. Azure Document DB 存储过程、触发器、自定义函数的实现

    阅读 大约需要 4 分钟 在上一篇随笔中记录的是关于Azure Cosmos DB 中SQL API (DocumentDB) 的简介和Repository 的实现.本随笔是Document DB 中 ...

  2. Azure CosmosDB (10) Azure Cosmos DB体系结构

    <Windows Azure Platform 系列文章目录> Azure Cosmos DB的体系结构分为以下几个部分: 1.Database Accounts Database Acc ...

  3. Azure Cosmos DB介绍及演示

    Azure Cosmos DB 是 Microsoft 提供的全球分布式多模型数据库服务.Cosmos DB是一种NoSql数据库,但是它兼容多种API.它支持SQL, MongoDB.Cassand ...

  4. Azure Cosmos DB (三) EF Core 操作CURD

    一,引言 接着上一篇使用 EF Core 操作 Azure CosmosDB 生成种子数据,今天我们完成通过 EF Core 实现CRUD一系列功能.EF Core 3.0 提供了CosmosDB 数 ...

  5. Azure Cosmos DB 使用费用参考

    之前在学习Cosmos DB 中SQL API(DocumentDB) 的时候,也就是之前做的一些笔记,看到有使用费用的一些介绍,就有兴趣的去了解了下,做了一下简单的总结. 想了解更多或是购买使用的还 ...

  6. Azure Cosmos DB (一) 入门介绍

    一,引言 今天是国庆.中秋双节房价的第三天,今天抽时间分享一篇关于使用Azure 提供的一项NoSql 服务-----Azure Cosmos DB.就有人问了,我听说过 MongoDB.Redis ...

  7. Azure Cosmos DB (二) SQL API 操作

    一,引言 还记得国庆期间,我们学习了一下关于Azure Cosmos DB 的一些基础知识以及Azure Cosmos DB 的几种支持数据库类型.今天就开始分享一些实战操作,如何通过Azure Po ...

  8. Azure Cosmos DB (四) 使用EF的SQL API 异地冗余

    一,引言 上一篇文章中,我们介绍到使用了EF Core 与Cosmos DB SQL API 进行结合开发.同时,大家在开发过程中一定要记得EF Core 不支持Cosmos DB 的迁移.今天我们启 ...

  9. Azure Cosmos DB (五) .Net Core 控制台应用

    一,引言 之前在讲Azure CosmosDB Core(SQL)核心的时候,使用了EF Core 的方式,引用了 "Microsoft.EntityFrameworkCore.Cosmos ...

随机推荐

  1. java 算法 - 冒泡排序

    冒泡排序: 冒泡排序是专门针对已有的一部分已经排序的数据进行排序的一种排序算法.假如你的数据中只有两个数据输乱序的,那么冒泡排序就是最快的.这种算法的核心思想就是扫描数据清单,找到乱序中相邻的两个数据 ...

  2. freeSWITCH之安装

    freeSWITCH 安装 官网教程 https://freeswitch.org/confluence/display/FREESWITCH/FreeSWITCH+First+Steps Windo ...

  3. 配置私有仓库(使用registry镜像搭建一个私有仓库)

    在使用Docker一段时间后,往往会发现手头积累了大量的自定义镜像文件,这些文件通过公有仓库进行管理并不方便:另外有时候只是希望在内部用户之间进行分享,不希望暴露出去.这种情况下,就有必要搭建一个本地 ...

  4. java NIO系列教程2

    7.FileChannel Java NIO中的FileChannel是一个连接到文件的通道.可以通过文件通道读写文件. FileChannel无法设置为非阻塞模式,它总是运行在阻塞模式下. 打开Fi ...

  5. Oracle数据库 中的基础的一些语法结构

    方括号里的内容为可选项 大括号是必填 1PL/SQL结构块 DECLARE /* * 声明部分——定义常量.变量.复杂数据类型.游标.用户自定义异常 */ BEGIN /* * 执行部分——PL/SQ ...

  6. git升级后jenkins的报错

    1.首先卸载原有的git #yum remove git 2.源码安装新版本的git https://www.kernel.org/pub/software/scm/git/ 下载最新的版本,然后编译 ...

  7. 11.Proxy

    Proxy Proxy 概述 Proxy 用于修改某些操作的默认行为,等同于在语言层面做出修改,所以属于一种"元编程"(meta programming),即对编程语言进行编程. ...

  8. Deep Q-Network 学习笔记(六)—— 改进④:dueling dqn

    这篇同样是完全没看懂 Orz,这里只做实现记录.. 要改动的地方只是在神经网络的最后一层做下调整即可. def create(self): neuro_layer_1 = 3 w_init = tf. ...

  9. WIN 10 初体验:期待越多失望越大

    我大多数时候使用 MacBook,不过 WIN 10(预览版)的推送还是让我忍不住升级玩玩——它是微软史上首款真正意义上的免费操作系统,正式版将与中国诸多互联网巨头联合提供升级工具分发这一体现了微软迎 ...

  10. Tomcat启动项目两次

    网上一搜,给出的答案都一样,不外乎:1.删除 Host 标签配置的 appBase="webapps"2.删除 Context 配置 此处这样做:重新添加Tomcat,选择好自己的 ...