Wednesday, 23 March 2011

Setting the first clause in a Lucene query to a SHOULD clause using Umbraco Examine

I'm using Umbraco Examine to index my content by setting up an Index on my Shared document type. I wanted to allow multiple search terms to be looked for in the index regardless of their order. So for example if a search for:

technology portable

or

portable technology

Both technology and portable will be searched for in the index. This was done using GroupOr methods but the problem was the first search term would always be included in the query as a MUST clause. Here is the code.

// Get the search criteria by using our searcher provider and looking only in the content tree of Umbraco.
var criteria = ExamineManager.Instance.SearchProviderCollection["SharedSearcher"].CreateSearchCriteria(IndexTypes.Content);

// Build the search query.
Examine.SearchCriteria.IBooleanOperation query = null;

foreach (var searchTerm in nonEmptySearchTerms)
{
query = query == null ? criteria.GroupedOr(fields, searchTerm.Trim().MultipleCharacterWildcard()) :
query.Or().GroupedOr(fields, searchTerm.Trim().MultipleCharacterWildcard());
}

// Perform the search.
results = ExamineManager.Instance.Search(query.Compile());
results.OrderByDescending(x => x.Score); // Relevance.

The only changed required was in the criteria creation to set the default BooleanOperator to an or, and thus setting the first clause to be SHOULD instead of MUST. Here is the corrected line:

var criteria = ExamineManager.Instance.SearchProviderCollection["SharedSearcher"].CreateSearchCriteria(IndexTypes.Content, BooleanOperation.Or);

No comments: