6

I am new to Azure Search Service, and I wanted to use the hit highlighting feature of Azure Search Service. I am using the .NET SDK NuGet package for azure search.
I used SearchParameter object to mention the hit highlight fields and also the Pre and Post Tag that I require.

searchParameters.HighlightFields = new[] { "Description"};
searchParameters.HighlightPreTag = "<b>";
searchParameters.HighlightPostTag = "</b>";
_searchIndexClient.Documents.Search(searchText, searchParameters);

I am expecting something like this:
SearchText: best
Result (Description) : The best product
The issue is that I do not see any difference in the result with/without using hit highlight. (Description Field is searchable)
Am I missing something?

4

2 回答 2

7

命中突出显示结果通过类的Highlights属性公开SearchResultBase链接

于 2015-04-13T19:26:12.973 回答
4

Highlights 属性仅包含完整字段值的一部分。如果要显示完整的字段值,则必须将突出显示合并到字段值中。

这里有一个对我有用的片段:

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;
}

对于 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>"));
}

在视图中,您可以像这样使用它:

@model SearchResult<MySearchDocument>
@Html.Highlight(nameof(MySearchDocument.Name), Model)
于 2016-07-13T08:14:20.757 回答