Hit Highlighting in Azure Search Service

Hit highlighting results are exposed via the Highlights property of the SearchResultBase class: link


The Highlights property contains just a part of the full field value. If you want to show the full field value, you have to merge the highlights into your field value.

Here a snippet that works for me:

public static string Highlight<T>(string fieldName, SearchResult<T> fromResult) where T : class
{
    var value = fromResult.Document.GetType().GetProperty(fieldName).GetValue(fromResult.Document, null) as string;

    if (fromResult.Highlights == null || !fromResult.Highlights.ContainsKey(fieldName))
    {
        return value);
    }

    var highlights = fromResult.Highlights[fieldName];

    var hits = highlights
        .Select(h => h.Replace("<b>", string.Empty).Replace("</b>", string.Empty))
        .ToList();

    for (int i = 0; i < highlights.Count; i++)
    {
        value = value.Replace(hits[i], highlights[i]);
    }

    return value;
}

For ASP.Net MVC

public static MvcHtmlString Highlight<T>(this HtmlHelper htmlHelper, string fieldName, SearchResult<T> fromResult) where T : class
{
    var value = fromResult.Document.GetType().GetProperty(fieldName).GetValue(fromResult.Document, null) as string;

    if (fromResult.Highlights == null || !fromResult.Highlights.ContainsKey(fieldName))
    {
        return MvcHtmlString.Create(htmlHelper.Encode(value));
    }

    var highlights = fromResult.Highlights[fieldName];

    var hits = highlights
        .Select(h => h.Replace("<b>", string.Empty).Replace("</b>", string.Empty))
        .ToList();

    for (int i = 0; i < highlights.Count; i++)
    {
        value = value.Replace(hits[i], highlights[i]);
    }

    return MvcHtmlString.Create(htmlHelper.Encode(value).Replace("&lt;b&gt;", "<b>").Replace("&lt;/b&gt;", "</b>"));
}

In the View you can use it like this:

@model SearchResult<MySearchDocument>
@Html.Highlight(nameof(MySearchDocument.Name), Model)