Sitecore Search and Indexing: Creating a simple search

With Sitecore 7, Sitecore introduced the new Sitecore.ContentSearch API which out of the box can query Lucene and SOLR based index’s.

Searching the index’s has been made easier through Linq to Sitecore that allows you to construct a query using Linq, the same as you would use with things like Entity Framework or Linq to SQL.

To do a query you first need a search context. Here I’m getting the a context on one of the default index’s:

using (var context = ContentSearchManager.GetIndex("sitecore_web_index").CreateSearchContext())
{
    ...
}

Next a simple query would look like this. Here I’m doing a where parameter on the “body” field:

using (var context = ContentSearchManager.GetIndex("sitecore_web_index").CreateSearchContext())
{
    IQueryable<SearchResultItem> searchQuery = context.GetQueryable<SearchResultItem>().Where(item => item["body"] == “Sitecore”)
}

But what if you want to add a search to your site. Typically you would want to filter on more than one field, what the user enters may be a collection of words rather than an exact phrase and you’d also like some intelligent ordering to your results.

Here I am splitting the search term on spaces and then building a predicate that has an “or” between each of its conditions. For each condition rather than doing a .Contains on a specific field, I’m doing it on a content field that will contain data for all fields in the item.

using (var context = ContentSearchManager.GetIndex("sitecore_web_index").CreateSearchContext())
{
    IQueryable<SearchResultItem> query = context.GetQueryable<SearchResultItem>();

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

    foreach (string term in criteria.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
    {
        predicate = predicate.Or(p => p.Content.Contains(searchTerm.Trim()));
    }

    SearchResults<SearchResultItem> searchResults = query.Where(predicate).GetResults();

    results = (from hit in searchResults.Hits
                        select hit.Document).ToList();
}

The intelligent ordering of results you will get for free based on what was search for.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s