Last updated by maurice 5 years ago


When the search method returns a collection of domain object hits (which it does by default or when result: "every"@), you can provide a @Closure that is called for each search result hit.

Before being called the Closure is cloned, so it is made thread-safe.

The Closure is called with the following parameters:

  • @highlighter@ - An instance of CompassHighlighter for that hit
  • @index@ - The search result index
  • @sr@ - The search-result object that will be returned by the search method. Normally this is a Map@, so you can store your arbitrary highlight data there. When @result: "every" it is the List of domain objects


With a typical search method invocation:

// This closure does the per-hit highlighting
// sr is the actual Map returned by search, so use that for storage
def songHighlighter = { highlighter, index, sr ->
    // lazy-init the storage
    if (!sr.highlights) {
        sr.highlights = []

// store highlighted song lyrics; "lyrics" is a // searchable-property of the Song domain class sr.highlights[index] = highlighter.fragment("lyrics") }

// Do the search, passing he highlighter option def searchResult ="summer winds", withHighlighter: songHighlighter)

assert searchResult.highlights assert searchResult.highlights.size() == searchResult.results.size() assert (searchResult.highlights[0].indexOf("<b>summer</b>") > -1 && searchResult.highlights[0].indexOf("<b>winds</b>") > -1)

With the @result: "every"@:

// Here we define the highlight closure inline
// sr is the collection of matching domain classes,
// so we need to define the storage externally this time
def highlights = []
def songs = Song.searchEvery("summer winds", withHighlighter: { highlighter, index, sr ->
    // store highlighted song lyrics; "lyrics" is a
    // searchable-property of the Song domain class
    highlights[index] = highlighter.fragment("lyrics")

assert highlights.size() == songs.size() assert (highlights[0].indexOf("<b>summer</b>") > -1 || searchResult.highlights[0].indexOf("<b>winds</b>") > -1)