Computing statistics for the search results
Imagine a situation where you want to compute some basic statistics about the documents in the results list. For example, you have an e-commerce shop where you want to show the minimum and the maximum price of the documents that were found for a given query. Of course, you could fetch all the documents and count it by yourself, but imagine if Solr can do it for you. Yes it can and this recipe will show you how to use that functionality.
How to do it…
Let’s start with the index structure (just add this to the fields section of your schema.xml file):
The example data file looks like this:
Let’s assume that we want our statistics to be computed for the price field. To do that, we send the following query to Solr:
The response Solr returned should be like this:
As you can see, in addition to the standard results list, there was an additional section available. Now let’s see how it works.
How it works…
The index structure is pretty straightforward. It contains three fields—one for holding the unique identifier (the id field), one for holding the name (the name field), and one for holding the price (the price field).
The file that contains the example data is simple too, so I’ll skip discussing it.
The query is interesting. In addition to the q parameter, we have two new parameters. The first one, stats=true, tells Solr that we want to use the StatsComponent, the component which will calculate the statistics for us. The second parameter, stats.field=price, tells the StatsComponent which field to use for the calculation. In our case, we told Solr to use the price field.
Now let’s look at the result returned by Solr. As you can see, the StatsComponent added an additional section to the results. This section contains the statistics generated for the field we told Solr we want statistics for. The following statistics are available:
- min: The minimum value that was found in the field for the documents that matched the query
- max: The maximum value that was found in the field for the documents that matched the query
- sum: Sum of all values in the field for the documents that matched the query
- count: How many non-null values were found in the field for the documents that matched the query
- missing: How many documents that matched the query didn’t have any value in the specified field
- sumOfSquares: Sum of all values squared in the field for the documents that matched the query
- mean: The average for the values in the field for the documents that matched the query
- stddev: The standard deviation for the values in the field for the documents that matched the query
You should also remember that you can specify multiple stats.field parameters to calculate statistics for different fields in a single query.
Please be careful when using this component on the multi-valued fields. It can sometimes be a performance bottleneck.