Faceted Search with Sitecore

Facets are used to group and classify content items, it’s used to aggregate the count of terms in a field to help a user filter their search more and more to get to the specific results they are after.

Search-Facets

As per the documentation of SOLR, facets are described as “… the arrangement of search results into categories based on indexed terms…”. faceting makes it really easy for the end users to look and explore for something which they are looking for. An example can be amazon.com which provides faceted navigation based on the selected keyword, which facilitates users to do look into specific category and narrowing down their results.

Sitecore+Search

Lucene and SOLR both provides support for Facets using ContentSearch API,which means you write facets one and that can be re-used for other search engines as well.
Using ContentSearch API we can use FacetOn() method on the IQueryable<T> instance to set what to facet on, and then call GetFactes() method to get the list of results.

context.GetQueryable<SearchResultModel>().Where(predicate).FacetOn(x => x[“ProperyName”], 1).GetFacets();

The second parameter to FacetOn() method is optional, it’s a min count and if we provide the min count, it means it’s going to return facets that is greater then equal >= to the value which has been set there.

Complete example:

using (IProviderSearchContext context = selectedIndex.CreateSearchContext())
{

var searchResults = context.GetQueryable<SearchResultItem>().Where(predicate).FacetOn(x => x[“ProperyName”], 1).GetResults();

// To check if we have any facet categories exists or not…
if (searchResults.Facets != null && searchResults.Facets.Categories.Any())

{

// Get all the facet categories…

// get facet category values and fetch facet name and aggregate count for each

// var facetName=facet.Name;

//  var facetCount= facet.AggregateCount;

}

}

If we want to facet based on multiple fields, we can just do it with adding chain of method calls and we should be all set to go.

context.GetQueryable<SearchResultItem>().Where(predicate).FacetOn(x => x[“Propery1Name”], 1).FacetOn(x => x[“Propery2Name”], 1).GetFacets();

Facets with tokenized fields:

Default field type in SOLR is tokenized which means it will split the string value in your index, and if the facet field value has space on it, it will be considered as two facets, as a workaround we should create a new computed untokenized index field and use that field instead.

Please see the below page for more details:

Sitecore Drop List Faceting Phrase Space Issue with Solr Search

Hope this helps.

Happy learning  and wish you all a very happy New Year 2018 🙂