Implementing search on web sites is a very common occurrence and this article is written to present a very simple approach to getting your Sitecore web site going using Lucene.net and Sitecore 6 or higher. Our approach will be the following: building the search box control, build the search results control and implement the Lucene index for the web database.
Overview
Lucene.net is an open source information retrieval software library that can be used by any application that requires full text indexing and searching capability. Sitecore CMS natively supports Lucene.net as a search and indexing engine and is used as the primary search framework for the platform.
Building the search box control
Though you may choose to implement user controls “sublayouts”, web controls or renderings when building UI components for Sitecore CMS, for this example I am going to use sublayouts. After you have created the layout using either Developer Center or Visual Studio, the code for the control will look like the following:
<script language="JavaScript" type="text/javascript">
function DoClick(nameButton) {
var searchTerm = $("input[name~=search]").text();
if ((searchTerm == "search")) {
return true;
}
}
</script>
<div class="search-form">
<fieldset>
<input id="SearchButton" name="SearchButton" type="hidden" />
<span class="field">
<input id="searchHeader" type="text" name="search" value="search" runat="server" />
</span>
<div class="submit">
<input type="submit" value="search" onclick="javascript: DoClick('SearchButton')" />
</div>
</fieldset>
</div>
Note: The javascript function DoClick() uses jQuery to retrieve the value of the search input textbox. So the layout that will use this component must have a reference to the jQuery library to work. It is also important to make considerations for implementing jQuery with no conflicts. This will be discussed in a separate article.
The code behind for the sublayout will look like the following:
public partial class SearchBox : System.Web.UI.UserControl
{
string searchTerm = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!String.IsNullOrEmpty(Request.QueryString["q"]))
{
string queryTerm = Request.QueryString["q"];
searchHeader.Value = queryTerm;
}
}
if (IsPostBack)
{
searchTerm = searchHeader.Value;
if ((searchTerm != "search"))
{
string url = "/SearchResults.aspx?q=" + searchTerm;
Response.Redirect(url);
}
else
{
return;
}
}
}
}
Note: The string url is set to redirect to the SearchResults.aspx page passing the query string that contains the search term from the text box.