I have regularly performed LINQ predicates when querying CosmosDB specific documents. However, today I filled up my CosmosDB with 100 k+ documents. The performance was very slow. As the SQL Query in the Azure Portal was noticeably faster, I tried using SqlQuerySpec. Voilá! It worked so much faster.
Can anyone tell me the what is happening under the hood, when using Linq predicates with CosmosDB and why it slows my queries down?
The below code is used in my method for getting the document. NB: The id is the partition key in this case.
var collectionUri = UriFactory.CreateDocumentCollectionUri(CDBdatabase, CDBcollection);
var sqlStatement = new SqlQuerySpec
{
QueryText = "SELECT * FROM c where c.id = @id",
Parameters = new SqlParameterCollection()
{
new SqlParameter("@id", consumerId),
},
};
IDocumentQuery<T> query = documentClient.CreateDocumentQuery<T>(
collectionUri,
sqlStatement,
.AsDocumentQuery();
List<ConsumerDetails> results = new List<ConsumerDetails>();
while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<ConsumerDetails>());
}
return results.FirstOrDefault();
Versus, the slower code:
return documentClient.CreateDocumentQuery<ConsumerDetails>(
collectionUri,
.Where(f => f.Id == consumerId).AsEnumerable().FirstOrDefault();
ReadDocument()will be faster than a query, always (1 RU for 1KB doc, for example), as it doesn't need to go through the query engine. - David MakogonConsumerDetailsDTO looks like? Did you try providing the partition key value as part of theFeedOptionsobject on the LINQ approach? Did you try doing.AsDocumentQueryandExecuteNextAsyncon the linq query? - Nick Chapsas