My solution for this was to boost the score for templates of the page type. This is achieved by including another predicate statement in my search logic that boosts templates of the page type (by 4.0f) along with an or statement with no boost for items not of those templates. This or statement is required otherwise items that weren't of the page type would not be included in the results - because we use and statements to join the outer predicates together.
pubic class Searcher { var searchIndex = ContentSearchManager.GetIndex("MySearchIndex"); // Get the search index var searchPredicate = BuildSearchPredicate(searchRequest); // Build the search predicate using (var searchContext = searchIndex.CreateSearchContext()) // Get a context of the search index { var searchResults = searchContext.GetQueryable<SearchModel>().Where(searchPredicate); // Search the index for items which match the predicate } } public static Expression<Func<SearchModel, bool>> BuildSearchPredicate(SearchRequestModel searchRequest) { var predicate = PredicateBuilder.True<SearchModel>(); // Items which meet the predicate predicate = predicate.And(GetEqualsSearchPredicate(searchRequest.SearchTerm)); // Boost templates predicate = predicate.And(GetBoosterPredicate()); return predicate; } private static Expression<Func<SearchModel, bool>> GetBoosterPredicate() { var predicate = PredicateBuilder.True<SearchModel>(); // Items which meet the predicate predicate = predicate.Or(x => x.TemplateName == "Content Page").Boost(4.0f); predicate = predicate.Or(x => x.TemplateName != "Content Page"); return predicate; } private static Expression<Func<SearchModel, bool>> GetSearchPredicate(string searchTerm) { var predicate = PredicateBuilder.True<SearchModel>(); // Items which meet the predicate predicate = predicate.Or(x => x.DispalyName.Equals(searchTerm)).Boost(2.0f); predicate = predicate.Or(x => x.Introduction.Equals(searchTerm)).Boost(2.0f); predicate = predicate.Or(x => x.Maintext.Equals(searchTerm)).Boost(2.0f); // Cut down logic here for demo purposes... return predicate; }As the above demo shows we join the main search predicate logic GetSearchPredicate with the template boosting predicate GetBoosterPredicate to create a single search predicate which will return the matching results.
As with any boosting/search logic it's important to thoroughly test to ensure the expected results are being returned across a range of search terms.
No comments:
Post a Comment