阅读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);
}
答案 0 :(得分:1)
您可以直接绑定到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);
}
}
答案 1 :(得分:0)
我更愿意利用Azure Cosmos DB的存储过程编程并批量删除单个存储过程中的文档,以获得更好的性能(网络流量延迟,事务的存储开销等)。有关详细信息,请参阅here。
要创建存储过程,您可以以简单的方式在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");
答案 2 :(得分:0)
我合并了:
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();
}