Monday, June 29, 2015

Getting Started with Sitecore Content Search using Lucene or Solr

Using Sitecore Content Search with Solr is basically identical to that with Lucene at the general use level, with the exception of the configuration.  Solr does have some more advanced features that Lucene does not have. 
To get started though with either all we need is a search context.  We can get this using the context item (or any item for that matter).  We simply cast the item to the SitecoreIndexableItem class and pass it into ContentSearchManager.CreatesearchContext and that will give us our context.

This is generally set up as:
using (var context = ContentSearchManager.CreateSearchContext((SitecoreIndexableItem)item)){
   //search code….
}

From inside this context we can get our search results by calling the generic method GetQueryable that takes all types that derive from SearchResultItem on our context and using Linq to filter our results.

An example where we get all items under the current item:
var results = context.GetQueryable<SearchResultItem>().Where(i => i.Paths.Contains(item.ID));

If you have custom fields you want to search on it is highly recommended that you create a class that derives from SearchResultItem and add your fields as properties.  What is really nice with this is that Sitecore content search will reflect on this class and do the search on those properties.

An example with an item with an author field:
public class MyCustomResultItem: SearchResultItem{
   
public string Author { get; set; }
}
var results = context.GetQueryable<MyCustomResultItem>().Where(i => string.Equals(i.Author,”me”));

At this point you can iterate through results and get the items using .GetItem() on each resulting item.

No comments:

Post a Comment