Take the 2-minute tour ×

I have some code using Lucene that leaves the default conjunction operator as OR, and I want to change it to AND. Some of the code just uses a plain QueryParser, and that's fine - I can just call setDefaultOperator on those instances.

Unfortunately, in one place the code uses a MultiFieldQueryParser, and calls the static "parse" method (taking String, String[], BooleanClause.Occur[], Analyzer), so it seems that setDefaultOperator can't help, because it's an instance method.

Is there a way to keep using the same parser but have the default conjunction changed?

share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

The MultiFieldQueryParser class extends the QueryParser class. Perhaps you could simply configure an instance of this class rather than relying on its static methods? If you really need to configure the BooleanClause.Occur values, you could do it afterward.

String queryString = ...;
String[] fields = ...;
Analyzer analyzer = ...;

MultiFieldQueryParser queryParser = new MultiFieldQueryParser(fields, analyzer);

Query query = queryParser.parse(queryString);

// If you're not happy with MultiFieldQueryParser's default Occur (SHOULD), you can re-configure it afterward:
if (query instanceof BooleanQuery) {
    BooleanClause.Occur[] flags = ...;
    BooleanQuery booleanQuery = (BooleanQuery) query;
    BooleanClause[] clauses = booleanQuery.getClauses();
    for (int i = 0; i < clauses.length; i++) {
share|improve this answer
That's good thanks. The missing step was how to configure the Occur values afterwards. Another approach I'm toying with is that the code for MultiFieldQueryParser.parse is tiny, so I might just paste that into my application and modify it. It creates QueryParser instances itself, so I can just tweak it to set the default operator on them. –  Luke Halliwell Jun 10 '09 at 19:28
Within the iterated for loop, you can also use the following to change the conjunction per field: QueryParser parser = new QueryParser(Version.YOUR_VERSION, fields[i], new YourAnalyzer()); parser.setDefaultOperator(QueryParser.Operator.AND); clause.setQuery(parser.parse(clause.getQuery().toString(fields[i]))); –  Ina Dec 6 '12 at 17:32
add comment

Your Answer


