Several months ago, during one of the projects I have tried to construct a query with optimal faceting. The problem was that we need filters (fq) in the query but in the same time we need a faceting that was not filtered. To some point it was not possible in Solr – you had to make two queries. But now, you can do it with one query. Let’s meet LocalParams.
The begining
LocalParams lets you tag part of the query, for example:
q=*:*&fq={!tag=city}city:warszawa
After sending the above query to Solr it will remember (in the context of the same query) that tag named city covers the filter with a value of city: warszawa. Now suppose that we want to send a query to get all documents that have the warszawa value in the city field (lets suppose that the city field is multi valued). In addition, we want to Solr to show us the number of documents in all cities. Nothing could be simpler with the use of LocalParams – just use the parameter {!ex} in the faceting. This could possibly be done by sending the following query to Solr:
q=*:*&fq={!tag=miasto}city:warszawa&facet=true&facet.field={!ex=miasto}city
The above query will return documents that have the warszawa value in the city field and faceting calculated on the city field which is not narowed by the filter query, because we excluded that filter.
Query parser type
Of course, the use of LocalParams is not limited to faceting. One of the interesting examples is a type handler definition. If we use standard query parser, we can change its type for a particular query with this structure:
q={!type=dismax qf=city}warszawa
The above query will use the dismax query parser and pass the qf=city parameter to it along with the warszawa value in the q parameter.
Logical operator
Changing the default logical operator using LocalParams is also very simple:
q={!q.op=AND}warszawa praga
The above query uses the AND logical operator for terms contained in the parameter q, which are warszawa and praga.
Parameter dereferencing
Additionally, by using LocalParams we can achieve an interesting feature – the parameters dereferencing. For example, if we want to use your own parameter names in queries, we can do it this way:
q={!type=dismax qf=city v=$pmiasto}&pmiasto=warszawa
Solr does not support default parameter named pmiasto, but with the key v (meaning value) and use of the reference operator $ it was possible to transfer the value of such a named parameter to the query.
I recommend that everyone who wants to use this feature in your application to play with LocalParams and find out if they fit your needs.
More information
Actual information about LocalParams and Solr can be found at Apache Solr wiki at the following address: http://wiki.apache.org/solr/LocalParams.