阅读 Azure 门户后,我了解了如何通过 Azure Functions 使用 CosmosDB 进行
POST
、PUT
和 GET
操作。但是删除,我不明白该怎么做。
我应该使用哪些绑定。它应该通过 sql 查询还是集合的方法(例如Remove())发生?
[**FunctionName**("EmployeeDocumentDB")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", "put", "delete", Route = "EmployeeDocumentDB/partitionkey/{key}/id/{id}")]HttpRequestMessage req,
[DocumentDB(
databaseName: "MyDatabase",
collectionName: "MyCollection",
ConnectionStringSetting = "CosmosDBEmulator")] ICollector<Person> outputDocument,
TraceWriter log)
{
dynamic data = await req.Content.ReadAsAsync<Person>();
return req.CreateResponse(HttpStatusCode.Accepted);
}
我组合:
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "delete")] HttpRequest req,
[CosmosDB(databaseName: "storage", collectionName: "pizza", Id = "{Query.id}", PartitionKey = "{Query.storeId}", ConnectionStringSetting = "..."] Document document,
[CosmosDB(databaseName: "storage", collectionName: "pizza", ConnectionStringSetting = ...)] DocumentClient client)
{
string storeId = req.Query["storeId"];
if(document == null || string.IsNullOrEmpty(storeId))
return new BadRequestResult();
await client.DeleteDocumentAsync(document.SelfLink, new RequestOptions() { PartitionKey = new PartitionKey(storeId) });
return new OkResult();
}
我更愿意利用 Azure Cosmos DB 的存储过程编程,并批量删除单个存储过程中的文档,以获得更好的性能(网络流量延迟、事务的存储开销等)。欲了解更多详情,您可以参考这里。
要创建存储过程,您可以通过简单的方式在 Azure 门户上为您的集合创建它。您可以按照示例here来批量删除给定查询的文档。
对于您的azure功能,您可以调用以下代码来执行存储过程来批量删除文档:
StoredProcedureResponse<object> result = await client.ExecuteStoredProcedureAsync<object>(
UriFactory.CreateStoredProcedureUri("MyDatabase", "MyCollection", "bulkDeleteSproc"),
"SELECT c._self FROM c WHERE c.founded_year = 2008");
您可以通过直接绑定到
DocumentClient
本身来完成此操作,并以编程方式删除文档。
[FunctionName("DeleteDocument")]
public static async Task Run(
[TimerTrigger("00:01", RunOnStartup = true)] TimerInfo timer,
[DocumentDB] DocumentClient client,
TraceWriter log)
{
var collectionUri = UriFactory.CreateDocumentCollectionUri("ItemDb", "ItemCollection");
var documents = client.CreateDocumentQuery(collectionUri);
foreach (Document d in documents)
{
await client.DeleteDocumentAsync(d.SelfLink);
}
}
请参阅 CosmosDBSamples
对于那些需要控制文档长度(即滑动窗口)的人来说,在 cosmo 容器中使用 TTL 是比通过 azure 函数删除文档更好的选择。只需进入“设置”,然后进入“生存时间”,快速计算一下,就可以了。我多留了几秒钟,以防出现延迟峰值。