Today, I created an example to demonstrate how BooleanQuery works and two different ways to construct a boolean query, using default constructor and using query builder. The construction using default constructor has been deprecated after Apache Lucene 5.3.0 and deleted in Apache Lucene 6.0.0. So we should use BooleanQuery.Builder to build queries.

Logo of Apache Lucene

This change has been annonced at the Apache Lucene’s news at 24 August 2015, the release of Apache Lucene 5.3.0 :

Lucene 5.3.0 Release Highlights:

API Changes

  • PhraseQuery and BooleanQuery are now immutable

Here’s an example showing the difference between them :

Query query = queryParser.parse("keyword");
BooleanQuery booleanQuery;
switch (mode) {
    
    // deprecated since 5.3.0
    // because PhraseQuery and BooleanQuery are immutable now
    case USE_CONSTRUCTOR:
        booleanQuery = new BooleanQuery();
        booleanQuery.add(query, Occur.MUST);

    // now, builder should be used instead
    case USE_BUILDER:
    default:
        booleanQuery = new BooleanQuery.Builder()
                .add(query, Occur.MUST)
                .build();
}

You can download my example code on github gsoc-lucene. Import the projet called boolean-query in Eclipse. Once finished, run the main method of class io.github.mincongh.App (Run As > Java Application).

The result will be printed in console :

Indexing /Users/mincong/Documents/GitHub/gsoc-lucene/boolean-query/src/main/resources/docs/apache-lucene-about.txt
Indexing /Users/mincong/Documents/GitHub/gsoc-lucene/boolean-query/src/main/resources/docs/apache-lucene-news.txt
Indexing /Users/mincong/Documents/GitHub/gsoc-lucene/boolean-query/src/main/resources/docs/gsoc.txt
3 File indexed, time taken: 135 ms

Using default constructor in boolean query (up to 5.2.x) ...
2 documents found. Time :24
File: /Users/mincong/Documents/GitHub/gsoc-lucene/boolean-query/src/main/resources/docs/apache-lucene-about.txt
File: /Users/mincong/Documents/GitHub/gsoc-lucene/boolean-query/src/main/resources/docs/apache-lucene-news.txt

Using query builder in boolean query (since 5.3.0) ...
2 documents found. Time :0
File: /Users/mincong/Documents/GitHub/gsoc-lucene/boolean-query/src/main/resources/docs/apache-lucene-about.txt
File: /Users/mincong/Documents/GitHub/gsoc-lucene/boolean-query/src/main/resources/docs/apache-lucene-news.txt