Search code examples
sitecoresitecore7

How to retrieve a total result count from the Sitecore 7 LINQ ContentSearch API?


In Lucene.Net, it is possible to retrieve the total number of matched documents using the TopDocs.TotalHits property.

This functionality was exposed in the Advanced Database Crawler API using an out parameter in the QueryRunner class.

What is the recommended way to retrieve the total result count using Sitecore 7's new LINQ API? It does not seem possible without enumerating the entire result set. Here is what I have so far:

var index = ContentSearchManager.GetIndex("sitecore_web_index");
using (var context = index.CreateSearchContext())
{
    var query = context.GetQueryable<SearchResultItem>()
                       .Where(item => item.Content == "banana");

    var totalResults = query.Count(); // Enumeration
    var topTenResults = query.Take(10); // Enumeration again? this can't be right?

    ...
}

Solution

  • Try this:

    using Sitecore.ContentSearch.Linq; // GetResults on IQueryable
    
    var index = ContentSearchManager.GetIndex("sitecore_web_index");
    using (var context = index.CreateSearchContext())
    {
        var query = context.GetQueryable<SearchResultItem>()
                       .Where(item => item.Content == "banana");
        var results = query.GetResults();
    
    
        var totalResults = results.TotalSearchResults;
        var topTenResults = results.Hits.Take(10);
    
    ...
    }
    

    To get more info about sitecore and linq you can watch this session and look at this repo.