Lucene Search in Sitecore

Lucene is an open source search engine used in Sitecore CMS for indexing and searching the contents of the website. Here you will see the simple and easy way to perform Lucene search in Sitecore. Lucene search can be performed on any item or fields of item(s). In this post we will look at performing Lucene search on Sitecore item field.

We will use the default search index provided by Sitecore. Default search index i.e. sitecore_master_index. This default search index uses syncMaster search strategy which will rebuild automatically based on certain events. Every time you update, create or delete an item Sitecore runs a job that updates the indexes. The process is usually complete by the time you have saved or published an item. So as you do any changes to an item then it will automatically rebuild the search index.
For more information about search index strategies refer this blog: http://bit.ly/1rVMvB8
//Get the Search Index
using(var searchIndex = ContentSearchManager.GetIndex("sitecore_master_index").CreateSearchContext())
{
//Perform the search on index
var searchResult =
 searchIndex.GetQueryable<SearchResultItem>()
 .Where((item => item["ItemTitle"].Contains(SearchText)))
 .Where(item => item.Path.Contains("SearchItem"));
 
//Here we are searching on fieldname “ItemTitle” also only those items will be fetched whose path contains the string called “SearchItem”

    if (searchResult != null)
    {
     displaySearchResultRepeater.DataSource = searchResult;
     displaySearchResultRepeater.DataBind();
    }
}

// For displaying result in repeater control:
<asp:Repeater ID="displaySearchResultRepeater" OnItemDataBound="displaySearchResultRepeater_ItemDataBound" runat="server">
     <ItemTemplate>
         Title : <asp:Label ID="Title" runat="server"></asp:Label><br /><br />
         Description : <asp:Label ID="Description" runat="server"></asp:Label><br /><br/>
     </ItemTemplate>
 </asp:Repeater>
For displaying result you just need to bind SearchResultItem with the event called displaySearchResultRepeater_ItemDataBound. For getting the result on the repeater data bound event you have to do the following:
var currentItem = (SearchResultItem) e.Item.DataItem;
var item = currentItem.GetItem();
 
Label Title = (Label) e.Item.FindControl("Title");
Label Description = (Label)e.Item.FindControl("Description");
 
Title.Text = item["ItemTitle"];
Description.Text = item["ItemDescription"];
Output:  when we pass “Item” in SearchText (e.g. SearchText = Item)
Output