Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get Count for paging in ravenDB

Tags:

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();
}

But 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?

like image 575
NiladriBose Avatar asked Aug 17 '11 13:08

NiladriBose


2 Answers

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

var results = _session
    .Query<T>()
    .Statistics(out stats)
    .Take(0)
    .ToArray();
like image 56
Thomas Freudenberg Avatar answered Sep 19 '22 20:09

Thomas Freudenberg


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);
...
like image 30
biofractal Avatar answered Sep 19 '22 20:09

biofractal