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
1 Answer
Reset to default 1You 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.