Reputation: 109
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;
}
Upvotes: 5
Views: 9170
Reputation: 877
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;
}
Upvotes: 0
Reputation: 8763
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.
Upvotes: 0
Reputation: 2062
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();
}
Upvotes: 7