Spring Solr Facet Query Examples

In this post we're going to look at a couple of Solr Facet Queries in Spring. We're going to take the Product Listing from NixMash Spring and create two Facet lists. The first will be a simple two-line output based on whether the products are available or not. The second will be a facet based on Product Categories.

Facet By Product Availability

Here's a ProductRepository Method. We create a FacetQuery object and specify what field we want our Facets based on, Product.AVAILABLE_FIELD.

Facet By Product Category

Next we're going to generate a Facet output based on the Product Category. We'll see it's very similar to our Facet by Availability except we're setting the Page Size with FacetQuery setFacetOptions(). I just wrote a post on setting FacetPage Size if you want to know more about that.

An Alternative Approach

For fun we'll look at an alternative approach to generating a Facet List by Category where JPA Annotations do most of the heavy lifting. Cool, huh?

Generating the Output

One of the nice features of Solr Facets is that you can drill down through the lists to view individual items or sub lists. We're simply going to display the results in Console.

Here is the code we'll use to generate the output for our Faceted Lists by Availability and Category. We create a FacetPage<Product> object from our Solr Facet Query which we use to populate a FacetFieldEntry Page listing we'll use for our output.

The Output

Here's the output of our two-line report on Product Availability.

Our Facet Listing by Category, all 11 of them!

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.

More Like This Post