The syntax you provide isn't so terribly wrong, actually, but may not turn out like you expect.
The query:
-record_id:123
Is not very useful. Lucene does not support pure negative queries. Lucene needs to have something to search for, if it is only given things not to match, it will match nothing.
Since your goal appears to be just filtering to only documents with recordState
= DRAFT
, having been given a valid query, it would be reasonable to return no results, since the user entered query isn't really any good.
A query like:
+recordState:DRAFT +(-record_id:123 anotherfield:terms)
would be just fine, and:
+recordState:DRAFT +(+record_id:123)
The +
inside the parentheses isn't really necessary, but it will also work without any problems.
If you want to detect a pure negative query like this, either by analyzing the query string, or iterating a BooleanQuery
return from the parser, something like:
BooleanQuery query = (BooleanQuery)parser.parse;
BooleanClause[] clauses = query.getClauses();
if (clauses.length == 1 && clauses[0].getOccur() == BooleanClause.Occur.MUST_NOT) {
booleanQuery.add(clauses[0]);
} else {
booleanQuery.add(query, BooleanClause.Occur.MUST);
}
Which might deal with the very specific case, but keep in mind, if the user can create a query of arbitrary complexity, they can just as well create the same issue nested somewhere in the query. Also, the query parser is not guaranteed to return a BooleanQuery
, so that's a bit of an assumption.