Boosting search results

If there are multiple hits for a given search string from different property fields, one can influence Lucene to prioritize a particular property field to search for over the other, resulting in a prioritized search result. This is called boosting.

For example, take a scenario where a user is searching with term "Anna" in a book store, with several books with book title having "Anna" as well as several books written by a author named "Anna". Since its the usual case to search for books by the book title, the hits which are coming from books whose title contains Anna should be more prominent and therefore shown first, and then should all other fields be considered.

Note that boosting may affect the site search performance and therefore be used only when necessary.

Following is a sample method that boost name over description.

/// <summary>
/// Boost the prominance given to display name when searching.
/// </summary>
public List<ProductModel> BoostSearch(WebSite webSite, SecurityToken token, string searchText, 
    ProductModelBuilder productModelBuilder, BaseProductService baseProductService, 
    VariantService variantService, FieldDefinitionService fieldDefinitionService)
{
    var request = new QueryRequest(webSite.Language.ID, ProductCatalogSearchDomains.Products, token);

    var textTermClause = new MandatoryTagClause();
    foreach (var term in StringHelper.ExtractTerms(searchText))
    {
        var textClause = new OptionalTagClause();

        // Make the name have a high prominance by boosting it.
        var nameTag = fieldDefinitionService.Get(SystemFieldDefinitionConstants.Name).GetTagName();
        textClause.Tags.Add(new Tag(nameTag, term) { AllowFuzzy = true, Boost = 100f });

        var descriptionTag = fieldDefinitionService.Get(SystemFieldDefinitionConstants.Description).GetTagName();
        textClause.Tags.Add(new Tag(descriptionTag, $"*{term}*") { Boost = 10f });
        textTermClause.Tags.Add(textClause);
    }

    // Note the use of QueryTags instead of FilterTags for adding boost settings to query.
    request.QueryTags.Add(textTermClause);

    var response = Solution.Instance.SearchService.Search(request);
            
    // The id's in the searchresult can be connected to either baseproduct or variant and therefore need to try get from one and then the other:
    var productModels = response.Hits
        .Select(x => productModelBuilder.BuildFromBaseProduct(baseProductService.Get(new Guid(x.Id)),  webSite) ?? productModelBuilder.BuildFromVariant(variantService.Get(new Guid(x.Id))))
        .Where(p => p != null)
        .ToList();

    return productModels;
}

 

Is this page helpful?
Thank you for your feedback!