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>();
- Get items for specific template type –
predicate = predicate.And<SearchResultItem>(i => i.TemplateId == [Template ID]);
- Get items under specific node or Items from specific location in Sitecore –
predicate = predicate.And<SearchResultItem>(i => i.Paths.Contains([Location Item ID]));
- Get items for context language only –
predicate = predicate.And<SearchResultItem>(item => item.Language == Context.Language.Name);
- 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.