5

I have a cosmos db container with below fields (id,Category,Type). The partition key is Category. While using the Below query I need to pass Partition key also. But I have only ID value. How do I perform the operation using ReadItemAsync?. I am getting not found error.

private async Task<T> GetItem(string id)
        {
            
                ItemResponse<T> response = await this.MainContainer.ReadItemAsync<T>(id, new PartitionKey(id));
                return response.Resource;
         }

3 Answers3

7

If you do not know the partition key value, you can use GetItemQueryable instead:

public T GetItemAsync(string id)
{
    IQueryable<T> queryable = container.GetItemLinqQueryable<T>(true);
    queryable = queryable.Where<T>(item => item.Id == id);
    return queryable.ToArray().FirstOrDefault();
}
Vivek Sharma
  • 1,912
  • 1
  • 13
  • 15
0

If you only have the id for the item and this is a high volume query, you may want to explore a new partition strategy for this container. But if there are also a high volume of reads that do use category, you could look at using change feed to keep two copies of the data and find another property that can be used as it's partition key. If id is globally unique in your application, then this could be used as well.

Mark Brown
  • 8,113
  • 2
  • 17
  • 21
  • Thanks for your reply. i Have below fields ID, Name, Category and Cost columns. My search will be mostly in ID and another search in Name.Is that ok to create two container one with ID and one with Name as partitions? – DealZaap India Sep 06 '20 at 22:45
  • You want to optimize around your high volume queries such that you are as efficient as possible. So knowing how many operations or queries you will run over say per second, minute, hour, etc. is important in this type of database. I would read this article and follow the steps it takes to get to its most optimal design [How to model and partition data on Azure Cosmos DB using a real-world example](https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-model-partition-example) – Mark Brown Sep 07 '20 at 15:06
0

You could also pass PartitionKey.None as the second parameter.

private async Task<T> GetItem(string id)
{
           
    ItemResponse<T> response = await this.MainContainer.ReadItemAsync<T>(id, PartitionKey.None);
    return response.Resource;
}
Papa Stahl
  • 687
  • 8
  • 7