Boosting search results

If there are multiple hits for a given search string from different property fields, you can influence Lucene to prioritise a particular property field to search for over another, resulting in a prioritised search result. This is called boosting.

For example, if a user searches for the term "Anna" in a book store, that has several books with "Anna" in the title as well as several books written by an author named "Anna". Since the usual case is to search for books by the title, the hits coming from books with "Anna" in the title should be more prominent in the search results, and therefore shown first, and then all other fields should be considered.

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

The following is a sample method that boosts 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!