Highlighted Search Results with Spring Solr

Solr Highlighted Search Results are now available in the NixMash Spring repo and demo'd online here. We'll walk through how to add Highlighting to Solr Query results in this post.

In the Repository

Let's start in the Product Repository class where we'll see the Spring Solr Highlight Query specifics. We're going to return a HighlightPage<Product> collection instead of the typical Page<Product> for paged results. Everything else is standard Spring JPA logic with the addition of setting the HighlightOptions for the search results and the field or fields to which we apply highlighting. We use our Spring SolrTemplate Bean to perform a queryForHighlightPage() search.

Extracting the Highlights

An interesting aspect of displaying highlights of a Solr HighlightPage collection is extracting the Highlight Snippets from the individual HighlightPage Entries. Without this exchange of the Product's Name property with its Highlighted Snippet counterpart we would see the unhighlighted Name in our search results and no cool <b>matches</b>.

In the Controller

We're reusing the Solr Search Form to support both Solr Syntax queries and highlighting. This requires hitting different Solr Repository Queries so we see if the Query String is a “simple search” not containing any Solr Syntax Query characters (1).  A “simple search” enables Highlighting so we'll call the appropriate Repository Method by way of our Service Layer and convert the HighlightPage<Product> collection to a list using a similar Snippet Replacement logic we saw above. (2)

Testing

We're going to see our “Snippet Extraction” logic as a key component to our Solr Highlighting @Test. This time we're confirming that the Highlighted Snippets contain the highlighted search term.

A Thymeleaf Tip

One final tip if using Thymeleaf. You will need to use a th:utext field indication in your HTML to unescape the highlighted field. Otherwise you would see <b>matches</b> on the results rather than the cool yellow background or however else you're styling those highlights.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.

Posted February 03, 2016 10:52 AM EST

More Like This Post