最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - CosmosDB ReadItemAsync with no partition key - Stack Overflow

programmeradmin4浏览0评论

I am trying to retrieve a document from Azure Cosmos DB without a partition key using this code

Container container = cosmosClient.Value.GetContainer(databaseId, containerId);
var retrieved = await container.ReadItemAsync<Doc>(id, PartitionKey.None);

This always gives a 404 not found error. If I pass the partition key

var retrieved = await container.ReadItemAsync<Doc>(id, new PartitionKey("1234"));

Then it works ok. I don't know the partition though, so how can I make this work?

I am trying to retrieve a document from Azure Cosmos DB without a partition key using this code

Container container = cosmosClient.Value.GetContainer(databaseId, containerId);
var retrieved = await container.ReadItemAsync<Doc>(id, PartitionKey.None);

This always gives a 404 not found error. If I pass the partition key

var retrieved = await container.ReadItemAsync<Doc>(id, new PartitionKey("1234"));

Then it works ok. I don't know the partition though, so how can I make this work?

Share Improve this question edited Mar 25 at 13:49 Jamiec 136k15 gold badges141 silver badges199 bronze badges asked Mar 25 at 11:55 CraigCraig 36.8k35 gold badges121 silver badges202 bronze badges 1
  • The reason the Partition Key is needed is because the identity of a document is both the id + Partition Key. You can have documents with the same id but different Partition Key, but there cannot be documents with the same id AND Partition Key, any attempt to create duplicates results in HTTP 409 responses. – Matias Quaranta Commented Mar 25 at 14:42
Add a comment  | 

1 Answer 1

Reset to default 1

You would need to perform a cross-partition query. This is however an expensive operation.

var query = new QueryDefinition("SELECT * FROM c WHERE c.id = @id")
    .WithParameter("@id", id);
var iterator = container.GetItemQueryIterator<Doc>(query);
var results = new List<Doc>();
while (iterator.HasMoreResults)
{
    var response = await iterator.ReadNextAsync();
    results.AddRange(response);
}
var retrieved = results.FirstOrDefault(); // If you know the ID is unique.
发布评论

评论列表(0)

  1. 暂无评论