Solr Search Term Autocomplete with Spring MVC

NixMash Spring Solr Search now supports Autocomplete which we’ll cover in this post and is shown below. You can also check it out on the demo site.

On the Page

We’ll start on the client side. Below is the Javascript we add to our search form. We’re using the jquery-ui plugin for the .autocomplete javascript functionality and pointing our query to a Spring MVC source at /products/autocomplete which we’ll see next.

In the Controller

Below is our Spring MVC Method. Four points to mention.

  1. We add @ResponseBody since we’re returning JSON. The url of the query will be /products/autocomplete?term=blahblah
  2. We do a Solr Facet search to return words within the product title field. Otherwise we’d return the entire title
  3. We next iterate through the results and select only those containing the term fragment for display in the field dropdown
  4. This is an alternative to displaying Faceted search terms. We may want to return the entire field so we’re returning a List<Product> collection.

Here’s what it would look like if we returned a List<Product> as opposed to a Faceted Solr search result.

Our Tests

Here’s how we’ll test the autocomplete function.

  1. We mock the MVC SolrController but will retrieve actual results with the productService component instance.
  2. As I mentioned earlier, we’re using an autocomplete?term=blahblah query url. Our AUTOCOMPLETE_FRAGMENT constant is “ph” or something which we’ll test for next.
  3. We’ll convert the JSON response body (ex: [“photos”,”phantoms”]) to a List<String> with the Jackson ObjectMapper and confirm that our “ph” AUTOCOMPLETE_FRAGMENT is contained in each.

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.