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
In the Controller
Below is our Spring MVC Method. Four points to mention.
- We add @ResponseBody since we're returning JSON. The url of the query will be /products/autocomplete?term=blahblah
- We do a Solr Facet search to return words within the product title field. Otherwise we'd return the entire title
- We next iterate through the results and select only those containing the term fragment for display in the field dropdown
- 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.
Here's how we'll test the autocomplete function.
- We mock the MVC SolrController but will retrieve actual results with the productService component instance.
- 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.
- 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.