AlfredBauer
AlfredBauer

Reputation: 105

Delete document in CosmosDB through azure function

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

Upvotes: 4

Views: 5243

Answers (4)

T3nt4c135
T3nt4c135

Reputation: 112

For those who need to control their documents length i.e. A sliding window, using TTL within a cosmo container is a much better alternative than deleting documents through an azure function. Simply go to settings and then Time to live, do some quick mathz and you are set. I leave a few extra seconds in case I get a latency spike.

Upvotes: 0

Magnielcz
Magnielcz

Reputation: 31

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

Upvotes: 3

Wah Yuen
Wah Yuen

Reputation: 1619

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

Upvotes: 1

Bruce Chen
Bruce Chen

Reputation: 18465

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");

Upvotes: 1

Related Questions