Sometimes, it is good to be able to choose different query parsers in the same query. For example, imagine that you would like to use the Extended DisMax query parser for the main query, but in addition to this, we would like to use the field query parser for filter queries. This recipe will show you how to do it.
This recipe will show how we can use different query parsers in a single query.
Let's start with the following index structure (this should go to the
field
section in theschema.xml
file):<field name="id" type="string" indexed="true" stored="true" required="true" /> <field name="name" type="text" indexed="true" stored="true" /> <field name="category" type="string" indexed="true" stored="true" />
Now, let's index the following data:
<add> <doc> <field name="id">1</field> <field name="name">First Solr 4.0 CookBook</field> <field name="category">Books</field> </doc> <doc> <field name="id">2</field> <field name="name">Second Solr 4.0 CookBook</field> <field name="category">Books And Tutorials</field> </doc> </add>
So, if we search for all the documents using the Extended DisMax query parser and want to narrow our results to the Books And Tutorials category, then we can send the following query:
curl 'http://localhost:8983/solr/select?q=*:*&defType=edismax&fq={!term f=category}Books And Tutorials'
The results returned by Solr would be as follows:
<?xml version="1.0" encoding="UTF-8"?> <response> <lst name="responseHeader"> <int name="status">0</int> <int name="QTime">1</int> <lst name="params"> <str name="fq"> {!term f=category}Books And Tutorials </str> <str name="q">*:*</str> <str name="defType">edismax</str> </lst> </lst> <result name="response" numFound="1" start="0"> <doc> <str name="id">2</str> <str name="name">Second Solr 4.0 CookBook</str> <str name="category">Books And Tutorials</str> </doc> </result> </response>
As you can see, we got what we expected. So let's see how it works.
Our index structure and example data are not that relevant for this recipe, so I'll skip discussing them.
What we want to achieve is be sure that the data we filter will be properly processed, and we want to avoid thinking about any kind of query parsing and Lucene special characters escaping. In order to do this, we use the term query parser
. To inform Solr that we want to use this query parser in the filter query (the fq
parameter), we use local parameter syntax and send this filter query: {!term f=category}Books And Tutorials
. The !term
part of the filter query says which query parser we want to use, and the f
property specifies the field to which we want to send the provided Books And Tutorials
value.
That's all; as you can see in the provided results, everything works as intended.