How do I add highlighting to Solr Suggester results?

  • Page Owner: Not Set
  • Last Reviewed: 2019-11-04

There is highlighting that is build into a standard Solr query, but if I use the suggester component to return search term suggestions, rather than query results, how do I add highlighting to the part of the suggestion that matches the query?


Additional Posts

There are multiple ways to handle this, and it really depends on the type of suggestions you are looking for. The Solr Suggest component can return 1 word search suggestions, or even the entire field of a document. While working on a search revamp for Lurie, I needed 1 or 2 word search suggestions that would also have highlighting incorporated.

The issue is, when you're using the suggest component, you need to use the AnalyzingInfixLookupFactory to utilize highlighting. However, this AnalyzingInfixLookupFactory would only allow me to return either the entire page title, or 1 single word suggestion.

My fix was to utilize the FreeTextLookupFactory instead of the AnalyzingInfixLookupFactory. This allowed me to return more than 1 word suggestions, but this option does not have highlighting built in. If I figure out another way to incorporate highlighting then I will update this answer, but the workaround I've used is to iterate through the entire suggestion list and wrap the term in tags. This code also maintains the capitalization that the user has used in their search query.

suggestionList.ForEach(x => x.Term = x.Term.Replace(q.ToLower(), $"<b>{q}</b>"));

Here is the suggester component that I'm currently working on, I will update this answer with the final version when it goes live. If anyone has more input or suggestions for better ways to handle this, let me know. There is great documentation from Solr for the suggest component, but when you start to tweak things it can feel like a lot of trial and error.

<searchComponent name="suggest" class="solr.SuggestComponent">
    <lst name="suggester">
      <str name="name">mySuggester</str>
      <str name="lookupImpl">FreeTextLookupFactory</str>
      <str name="dictionaryImpl">DocumentDictionaryFactory</str>
      <str name="field">Title_txt_en_split</str>
      <str name="ngrams">3</str>
      <str name="maxShingle">0</str>
      <str name="separator"> </str>
      <str name="suggestFreeTextAnalyzerFieldType">text_general</str>
      <str name="build">true</str>
    </lst>
  </searchComponent>