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

StackOverflow https://stackoverflow.com/questions/17540145

  •  02-06-2022
  •  | 
  •  

سؤال

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?

    ...
}
هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top