Thomas Segato
Thomas Segato

Reputation: 5221

Cosmos DB read a single document without partition key

A container has a function called ReadItemAsync. The problem is I do not have the partition key, but only the id of the document. What is the best approach to get just a single item then?

Do I have to get it from a collection? Like:

var allItemsQuery = VesselContainer.GetItemQueryIterator<CoachVessel>("SELECT * FROM c where c.id=....");

var q = VesselContainer.GetItemLinqQueryable<CoachVessel>();
var iterator = q.ToFeedIterator();

var result = new List<CoachVessel>();
while (iterator.HasMoreResults)
{
    foreach (var item in await iterator.ReadNextAsync())
    {
        result.Add(item);
    }
}

Upvotes: 6

Views: 9325

Answers (2)

Scott Anderson
Scott Anderson

Reputation: 123

Try using ReadItemAsync like:

dynamic log = await container.ReadItemAsync<dynamic>(ID, PartitionKey.None);

Upvotes: 1

Mark Brown
Mark Brown

Reputation: 8763

Posting as answer.

Yes you have to do a fan out query but id is only distinct per partition key so even then you may end up with multiple items. Frankly speaking, if you don't have the partition key for a point read then the model for the database is not correct. It (or the application itself) should be redesigned.

Additionally. For small, single partition collections this x-partition query will not be too expensive as the collection is small. However, once the database starts to scale out this will get increasingly slower and more expensive as the query will fan out to ever increasing numbers of physical partitions. As stated above, I would strongly recommend you modify the app to pass the partition key value in the request. This will allow you to do a single point read operation which is extremely fast and efficient.

Good luck.

Upvotes: 9

Related Questions