During my everyday work, I have seen many repeated queries, to Solr, with only one filter difference. When I asked why – I got anserws that it was necessary to get the faceting results for various filters. If you are using Solr version 1.4 or later, my suggestion is to use local params – what is it and how to use – this post will attempt to answer both questions.
Assumptions
In order to show how to use the local params with faceting let’s assume the following situation. In the index we have four fields defined:
- id – unique identifier,
- name – the company name,
- province – the province in which the company is located,
- city – the city where the company is located.
For the simplicity, I assumed that the fields id, province and the city are based on the string type. The field name is a text. Fields are not multivalued and the definition of types is the same as in the standard distribution of Solr.
Objective
What we want to achieve ? In addition to finding a company whose name matches the user-entered phrases, the user gives the name of the province and city. User must provide all parameter a simplification to make the example easier to understand. We want to show two types of faceting:
- cities in which the found companies are, but not narrowed to the selected province,
- all provinces in which there are companies that match the query.
Standard approach
The standard approach would rely on the generation of two queries:
q=PHRASE&fq=city:CITY&province:PROVINCE
q=PHRASE&facet=true&facet.field=city&facet.field=province
The first is responsible for the collection of companies that match the phrase entered and are narrowed to the city and province, while the second gives us the desired faceting without refinements.
Local params
Solr 1.4 brought an interesting feature – local params. In our case, what counts is that the tagging feature allows you to filter and eliminate the filters in faceting mechanism. These two queries can be replaced as follows:
q=PHRASE&fq={!tag=tagCity}city:CITY&fq={!tag=tagProvince}province:PROVINCE&facet=true&facet.field={!ex=tagCity,tagProvince}city&facet.field=!{ex=tagCity,tagProvince}province
How does it work ?
First of all, for each filter (the fq parameter) we define a unique tag by which we can refer to the filter. To do this we use the following structure {!tag=TAG_NAME}.
Then for each of the fields we want to use to do faceting we add information which filters should be excluded. In our case, we exclude the two filters in both fields when using faceting. To do this we use the following structure {!ex = TAG_NAME_1, TAG_NAME_2 ,…}.
A few words at the end
Of course, the functionality of local params is not only the faceting and the possibility of filter exclusion. I promise that in the future there will be another entry describing the wider opportunities offered by Solr and the local params functionality introduced in version 1.4.