Lucene Boost with LINQ in Sitecore 7 ContentSearch
Finally figured out how to boost certain fields using Sitecore 7’s
ContentSearch LINQ provider. Boosting provides relevance enhancements when a
search term is found within a field. For example, a search term found in a
documents title
or keywords
field is probably way more relevant than if its
found in the body
.
You may have stumbled across the Boost
extension method but couldn’t get it
to work.
The issue is that the Boost
extension method does not work with the ==
operator: you have to use a method like .Equals
or .Matches
. (I think I’ll
throw up another post with the other provided LINQ operators).
So if you have a document type like BlogSearchResultItem
:
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.SearchTypes;
public class BlogSearchResultItem : SearchResultItem
{
[ ]
public string Title { get; set; }
[ ]
public string Keywords { get; set; }
[ ]
public string Body { get; set; }
}
You can boost the search term using Boost
:
public SearchResults<BlogSearchResultItem> Search(string term)
{
using (var context = ContentSearchManager.GetIndex("blog_posts").CreateSearchContext())
{
var query = context.GetQueryable<BlogSearchResultItem>();
return query.Where(b =>
b.Title.Equals("test").Boost(2.0f) ||
b.Keywords.Equals("test").Boost(1.5f) ||
b.Body == "test").GetResults();
}
}
This should yield the following Lucene query:
title:test^2.0 keywords:test^1.5 body:test