Delete document in CosmosDB through azure function

后端 未结 3 1482
隐瞒了意图╮
隐瞒了意图╮ 2021-01-07 02:11

Reading the Azure portal I\'ve understood how to make a POST, PUT and GET operation with CosmosDB through the Azure Functions. But del

相关标签:
3条回答
  • 2021-01-07 02:14

    I combined:

    • HTTP trigger
    • CosmoDB DocumentClient Input
    • CosmoDB Input with look up ID from query string
    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();
            }
    
    0 讨论(0)
  • 2021-01-07 02:26

    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

    0 讨论(0)
  • 2021-01-07 02:31

    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");
    
    0 讨论(0)
提交回复
热议问题