开发者

Best way to get Count for paging in ravenDB

I need to find the number of documents that are in the raven database , so that I can properly page the documents out. I had the following implementation -

public int Getcount<T>()
{
    IQueryable<T> queryable = from p in _session.Query<T>().Customize(x =>x.WaitForNonStaleResultsAsOfLastWrite())
    select p;
    return queryable.Count();
}

Bu开发者_开发问答t if the count is too large then it times out.

I tried the method suggested in FAQs -

    public int GetCount<T>()
    {
        //IQueryable<T> queryable = from p in _session.Query<T>().Customize(x => x.WaitForNonStaleResultsAsOfLastWrite())
        //                          select p;
        //return queryable.Count();

        RavenQueryStatistics stats;
        var results = _session.Query<T>()
            .Statistics(out stats);

        return stats.TotalResults;
    }

This always returns 0.

What am I doing wrong?


stats.TotalResults is 0 because the query was never executed. Try this instead:

var results = _session
    .Query<T>()
    .Statistics(out stats)
    .Take(0)
    .ToArray();


The strange syntax to get the statistics tripped me up as well. I can see why the query needs to be run in order to populate the statistic object but the syntax is a bit verbose imo.

I have written the following extension method for use in my unit tests. It helps keep the code terse.

Extension Method

public static int QuickCount<T>(this IRavenQueryable<T> results)
{
    RavenQueryStatistics stats;
    results.Statistics(out stats).Take(0).ToArray();
    return stats.TotalResults;
}

Unit Test

...
db.Query<T>().QuickCount().ShouldBeGreaterThan(128);
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜