Sitecore Search and filtering

This is not something you can’t find on internet but I am sure I’ll write some content or tips which is not easily available. I worked on search many times and every time I came across with different scenarios.

Here I am writing about my recent work with Sitecore search (Lucene & Solr). I have used filtering in our search with the help of predicate builder. It gives more capabilities to apply multiple filters with single line code. I would love to use predicate builder while working on search or filtering the results.

Here are some tips which can help you to get specific results as per your requirements  –

Sitecore Search allows you to use Linq to perform your search queries and uses the IQueryable<T> interface.

using (var context = ContentSearchManager.GetIndex(ContextItem).CreateSearchContext())

var queryable = context.GetQueryable<SearchResultItem>();


Here ContextItem is SitecoreIndexableItem item. you don’t need to specify the index name here. It will automatically pick the index as per current item and database of current item. And queryable is a collection of index results.

Till yet we haven’t applied any type of filtering it is just to get the indexed items from the indexes which is created by Solr or Lucene.

Now to apply filters define a predicate builder as given below –

      var predicate = PredicateBuilder.True<SearchResultItem>();

  1. Get items for specific template type  –
    predicate = predicate.And<SearchResultItem>(i => i.TemplateId == [Template ID]);
  2. Get items under specific node or Items from specific location in Sitecore –
    predicate = predicate.And<SearchResultItem>(i => i.Paths.Contains([Location Item ID]));
  3. Get items for context language only  –
    predicate = predicate.And<SearchResultItem>(item => item.Language == Context.Language.Name);
  4. Get items which contains specific Keyword –
    predicate = predicate.And<SearchResultItem>(i => i.Content.Contains(Keyword));

Now once you applied all the conditions or created all the predicates then you just need to pass it into linq  –

var results= queryable .Where(builder).Select(i => (Item)i.GetItem());

it will give you the list of filtered items as per your filtering conditions.

I hope this post will be helpful to start with search and filtering in next post we will discuss about Indexing custom fields and search on specific field values.




This entry was posted in Sitecore, Sitecore Search and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s