Gravatar for fcote@coveo.com

Question by fcote, May 6, 2015 8:49 AM

How to obtain the total count of results when using GetAllResults()

From : https://developers.coveo.com/display/public/SC201504/Retrieving+Large+Sets+of+Items+Using+LINQ

When using the GetAllResults() method, how can you create a way to know the total amount of results or a mechanism to do paging/take/range ?

1 Reply
Gravatar for lbergeron@coveo.com

Answer by Luc Bergeron, May 6, 2015 8:58 AM

Hi,

You should use the GetAllResults() method only when you want to iterate over large sets of results. To get the total count, you should simply call the IQueryable<T>.Count() method as in the code sample below.

ISearchIndex index = ContentSearchManager.GetIndex("Coveo_web_index");
using (var context = index.CreateSearchContext()) {
    var queryable = context.GetQueryable<SearchResultItem>().Where(item => item.TemplateName == "Sample Item");

    int totalNumberOfResults = queryable.Count();
}

If you want to fetch pages of results, you can do it by calling Take() and Skip() methods as follow.

int firstResult = 20; // To skip the 2 first pages
int numberPerPage = 10;
IEnumerable<SearchResultItem> pageOfResults = queryable.Skip(firstResult).Take(numberPerPage);

I hope this helps

Ask a question