Delete document in CosmosDB through azure function

2019-02-19 18:09发布

问题:

Reading the Azure portal I've understood how to make a POST, PUT and GET operation with CosmosDB through the Azure Functions. But deleting, I don't understand how to do this.

Which bindings should I use. Should it occur either through sql query or collection's method, like 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);
    }

回答1:

You could do this by binding directly to the DocumentClient itself, and delete the Document programatically.

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

See CosmosDBSamples



回答2:

I would prefer to leverage the stored procedures programming for Azure Cosmos DB and delete the documents inside a single stored procedure in batch for better performance (network traffic latency, store overhead for transactions, etc.). For more details, you could refer to here.

For creating the stored procedure, you could create it for your collection on Azure Portal in a simple way. And you could follow the sample here for deleting documents in batch for a given query.

For your azure function, you could call the code below for executing the stored procedure to delete the documents in batch:

StoredProcedureResponse<object> result = await client.ExecuteStoredProcedureAsync<object>(
    UriFactory.CreateStoredProcedureUri("MyDatabase", "MyCollection", "bulkDeleteSproc"), 
    "SELECT c._self FROM c WHERE c.founded_year = 2008");