Modifying the highlight regular expression

Background

Highlighting of search terms in the result listing is usually handled by the <@s.Boldicize> Freemarker macro.

This uses a regular expression generated by the query processor to highlight occurrences of the search terms in result output.

This article details how to update the regular expression using a post datafetch hook script.

Process

Step 1. Post datafetch hook script

Create (or edit) the hook_post_datafetch.groovy script for the collection which is being queried.

Add the following code to the hook script then save. Changes take effect as soon as the hook script has been saved.

hook_post_datafetch.groovy
if ( transaction.response != null && transaction.response.resultPacket != null) {

  // Update the highlight regex
  // def customHighlightRegex=<SAMPLE REGEX>
  // eg. add highlight for the following #hashtag and Funnelback
  def customHighlightRegex="\s#hashtag\b|\bFunnelback\b";

  if (transaction.response.resultPacket.queryHighlightRegex != null) {
      // append to existing highlight expression
      transaction.response.resultPacket.queryHighlightRegex+="|"+customHighlightRegex;
  }
  else {
      // create the highlight expression
      transaction.response.resultPacket.queryHighlightRegex="(?i)"+customHighlightRegex
  }
}

Step 2: View the data model

Run a query and observe the response.resultPacket.queryHighlightRegex value in the data model to confirm that the custom highlight expression is being applied.