Tutorial :Using AND, OR and NOT in Solr Query



Question:

I am trying a Solr query which is like this

+field1:* AND (field2:1 OR field2:10) NOT(field3:value1 OR field3:value2)  

But field3 part of the query is not making any impact. It still brings record which has value1 or value2 in field3

Why is this?


Solution:1

Try this

+field1:* +(field2:1 OR field2:10) -(field3:value1 OR field3:value2)  


Solution:2

I think a AND / OR is missing between the two last blocks. It would then become something like :

+field1:* AND (field2:1 OR field2:10) AND NOT(field3:value1 OR field3:value2)  


Solution:3

You need to urlencode certain characters in the Solr query to meet UTF8 standards and the + (plus) symbol is one of them, as well as space, brackets etc.

Things to encode are:

Space => +  + => %2B  ( => %28  ) => %29  

and so forth, you can see an example of an encoded URL on the SOLR website: https://wiki.apache.org/solr/SolrQuerySyntax

Try:

str_replace(array('+','(',')',' '), array('%2B','%28','%29','+'), '+field1:* (field2:1 field2:10) -(field3:value1 field3:value2)');  

This should give you:

%2Bfield1:*+%2B%28field2:1+field2:10%29+-%28field3:value1+field3:value2%29  

IF your default query parser operation is set to OR, then any space between fields will be interpreted as an OR operator.

The above result is far from clean & readable, but it is a correctly formatted UTF8 string which Solr requires you to pass to it. You'll notice the difference as soon as you run it.

Why str_replace instead of urlencode? Well you can use urlencode because it will correctly format the string as UTF8 but it might format some string components that don't need to be encoded.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »