[Serverless] 使用 Azure Cosmos DB for NoSQL 的 API
什么是 Azure Cosmos DB for NoSQL?
Azure Cosmos DB for NoSQL 是用于处理文档数据模型的原生非关系服务。它可以使用灵活的架构任意存储原生 JSON 文档。数据会自动编制索引,并可使用专为 JSON 数据设计的 SQL 查询语言进行查询。使用适用于常用框架(如 .NET、Python、Java 和 Node.js)的 SDK 访问 API。
操作范例
1. 免费创建帐户
https://azure.microsoft.com/free
2. 创建数据库(Database)和容器(Container)
3. 在项目中使用 NuGet 安装 Microsoft.Azure.Cosmos 包
关于对象模型
3.1 验证客户端
CosmosClient client = new( accountEndpoint: "<azure-cosmos-db-nosql-account-endpoint>", authKeyOrResourceToken: "<azure-cosmos-db-nosql-account-key>");
3.2 获取数据库
Database database = client.GetDatabase("databasename");
3.3 获取容器
Container container = database.GetContainer("containername");
3.4 新建项
Product item = new( id: "68719518391", category: "gear-surf-surfboards", name: "Yamba Surfboard", quantity: 12, price: 850.00m, clearance: false ); ItemResponse<Product> response = await container.UpsertItemAsync<Product>( item: item, partitionKey: new PartitionKey("gear-surf-surfboards") );
3.5 读取项
ItemResponse<Product> response = await container.ReadItemAsync<Product>( id: "68719518391", partitionKey: new PartitionKey("gear-surf-surfboards") );
3.6 查询项
/* 使用 container.GetItemQueryIterator 对容器中的多个项执行查询。 使用此参数化查询查找指定类别中的所有项。 */ string query = "SELECT * FROM products p WHERE p.category = @category" var query = new QueryDefinition(query).WithParameter("@category", "gear-surf-surfboards"); using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(queryDefinition: query); /* 通过使用 feed.ReadNextAsync 循环访问每个结果页来分析查询的分页结果。 在每个循环的开头使用 feed.HasMoreResults 来确定是否还剩下任何结果。*/ List<Product> items = new(); while (feed.HasMoreResults) { FeedResponse<Product> response = await feed.ReadNextAsync(); foreach (Product item in response) { items.Add(item); } }
3.7 删除项
await this.container.DeleteItemAsync<Product>(id, new PartitionKey(id));
参考资料
快速入门:适用于 .NET 的 Azure Cosmos DB for NoSQL 库
Azure Cosmos DB for NoSQL 入门
Azure Cosmos DB 使用教程
Azure Cosmos DB 随笔教程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库