How to construct IQueryable query using Linq when I just need count without reading all documents in Document-Db database?

孤人 提交于 2019-12-24 08:34:40

问题


I need the number of documents stored in a collection in my Azure Cosmos Db database. How can I get the count using LINQ query on the IQueryable object?

docDbClient.CreateDocumentQuery<TResult>().Count()

If I do above, I am unable to follow it up with .AsDocumentQuery() method.


回答1:


This is my async implementation (use Count, for the sync version):

var count = await DocumentClient.
            CreateDocumentQuery<T>(CreateCollectionUri(), CreateFeedOptions()).
            Where(predicate).
            CountAsync();

where predicate is Expression<Func<T, bool>>




回答2:


You can try to use the following code to count the number of documents in your collection.

client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);

IQueryable<int> total = client.CreateDocumentQuery<int>(UriFactory.CreateDocumentCollectionUri("testdb", "testcoll"), "SELECT Value count(1) FROM c", new FeedOptions() { EnableCrossPartitionQuery = true });

Console.WriteLine("total: " + total.AsEnumerable().FirstOrDefault());

Query result:

If you capture the request (using fiddler etc), you will find that the client sdk send the same query {"query":"SELECT VALUE [{\"item\": Count(1)}]\r\nFROM root"} to the server when you execute your code docDbClient.CreateDocumentQuery<TResult>().Count().



来源:https://stackoverflow.com/questions/45183435/how-to-construct-iqueryable-query-using-linq-when-i-just-need-count-without-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!