Search code examples
solrsolrj

Negation in solr query


I am trying the following query and get only zero results (I am supposed to get 10 results according to my dataset)

http://mymachine:8983/solr/select/?q=-(HOSTID:302)

I also tried the below query and got zero results yet again.

http://mymachine:8983/solr/select/?q=NOT(HOSTID:302)

However, I get 10 results(expected) when I put the query this way,

http://mymachine:8983/solr/select/?q=-(HOSTID:302)AND(*:*)

Why is this strange thing happening? Is it a bug in solr or am I missing something?


Solution

  • Ahmet Arslan from the solr mailing list helped me with a solution. Just mentioning it here for future benefits.

    Solr converts top level negative query (-field:something) into q=+: -field:something

    It seems that you are missing that part.

    org.apache.solr.search.QueryUtils

    `/** Fixes a negative query by adding a MatchAllDocs query clause.
      * The query passed in *must* be a negative query.
      */
     public static Query fixNegativeQuery(Query q) {
       BooleanQuery newBq = (BooleanQuery)q.clone();
       newBq.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
       return newBq;
     }`