4

I am trying to delete an item from CosmosDB collection. I am calling using

ItemResponse<Device> response = await _deviceCapabilityContainerName.DeleteItemAsync<Device>(device.deviceId, new PartitionKey(device.deviceId));

I have seen posts doing exactly the same only difference being, in my case both the values PartitionKey and id are same. I am constantly getting 404 Resource Not found error. How can I delete records in this case. I don't want to drop the collection and re-create.

nikhil
  • 75
  • 1
  • 10

1 Answers1

5

Newest

Data Format.

{
"id": "002",
"deviceid": "002",
"_rid": "Jx1nAMAZtRYEAAAAAAAAAA==",
"_self": "dbs/Jx1nAA==/colls/Jx1nAMAZtRY=/docs/Jx1nAMAZtRYEAAAAAAAAAA==/",
"_etag": "\"00000000-0000-0000-5a4b-b12502fe01d6\"",
"_attachments": "attachments/",
"_ts": 1594778419
}

enter image description here

Code.

using System;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections.Generic;
using System.Net;
using Microsoft.Azure.Cosmos;
using System.Linq;

namespace CosmosDB
{
    class Program
    {
        // <Main>
        public static async Task Main(string[] args)
        {
            try
            {
                Console.WriteLine("Beginning operations...\n");
                CosmosClient client = new CosmosClient("https://localhost:8081/", "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");
                Database database = await client.CreateDatabaseIfNotExistsAsync("Items");
                Container container = database.GetContainer("test");
                // Query for an item
                FeedIterator<response> feedIterator = container.GetItemQueryIterator<response>("SELECT * FROM c");

                List<Task> concurrentDeleteTasks = new List<Task>();

                while (feedIterator.HasMoreResults)
                {
                    FeedResponse<response> res = await feedIterator.ReadNextAsync();
                    foreach (var item in res)
                    {                            concurrentDeleteTasks.Add(container.DeleteItemAsync<response>(item.id, new PartitionKey(item.deviceid)));
                    }
                }
                await Task.WhenAll(concurrentDeleteTasks.Take(3));
            }
            catch (CosmosException de)
            {
                Exception baseException = de.GetBaseException();
                Console.WriteLine("{0} error occurred: {1}", de.StatusCode, de);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
            }    
            finally
            {
                Console.WriteLine("End of demo, press any key to exit.");
                Console.ReadKey();
            }
        }
        public class response
        {
            public string id { get; set; }
            public string deviceid { get; set; }
            public string _rid { get; set; }
            public string _self { get; set; }
            public string _etag { get; set; }
            public string _attachments { get; set; }
            public long _ts { get; set; }
            }
        }
    }

PRIVIOUS

Your error is that partion key is not name but value of the partion key.

container.DeleteItemAsync<response>(item.id, new PartitionKey(item.adress)

For more detail, you can refer my answer in this post.

Jason Pan
  • 15,263
  • 1
  • 14
  • 29
  • Yeah I know that. But the thing is my object, deviceId acts as the Id and it is also the PartitionKey, and I specifically do not have separate Id in my object. – nikhil Jul 14 '20 at 14:26
  • @nikhil There may be no way. When I tried before, I found that id is a required field, and `Partion key: /ids` is also a required field. It is recommended to modify the `id` of the Partion key to `ids` and the `value` to `"_"+ value`. Try it. – Jason Pan Jul 14 '20 at 14:34
  • I think I will have the need to modify the objects. These objects were not created by me. I don't know how they were adding the data earlier without "id" field. Anyway thanks for the answer. – nikhil Jul 14 '20 at 14:40
  • @nikhil The previous answer is not rigorous. I think that as long as the record can be successfully added, there must be a way to delete it. You can take a look at my updated answer first. If it is convenient, can you provide your data format? Please do not include sensitive information. I will continue to study here and will tell you if it is feasible. – Jason Pan Jul 15 '20 at 02:08
  • I was able to solve this. Earlier on getting the response from DB `id` field was not getting set(because of how the models were designed.). I made some changes in the model, in order to set the id info as well. After that, my code became similar to what you've mentioned and is working as expected. – nikhil Jul 15 '20 at 07:59