Question

How to use booleanQuery with StandardAnalyzer in Lucene Search?

Was it helpful?

Solution

I presume you are referring to parsing boolean queries using the QueryParser object, correct? The Lucene query syntax documentation should have everything you need.

OTHER TIPS

According to the document, boolean queries should be created once by BooleanQuery.QueryBuilder and then considered immutable. See BooleanQuery.Builder.add(org.apache.lucene.search.BooleanClause)

The code example can be found by http://programtalk.com/java-api-usage-examples/org.apache.lucene.util.QueryBuilder/ and one example given is:

public Query parse(Type type, String fieldName, Object value) throws IOException {
    final String field;
    MappedFieldType fieldType = context.fieldMapper(fieldName);
    if (fieldType != null) {
        field = fieldType.name();
    } else {
        field = fieldName;
    }
    /*
     * If the user forced an analyzer we really don't care if they are
     * searching a type that wants term queries to be used with query string
     * because the QueryBuilder will take care of it. If they haven't forced
     * an analyzer then types like NumberFieldType that want terms with
     * query string will blow up because their analyzer isn't capable of
     * passing through QueryBuilder.
     */
    boolean noForcedAnalyzer = this.analyzer == null;
    if (fieldType != null && fieldType.tokenized() == false && noForcedAnalyzer) {
        return blendTermQuery(new Term(fieldName, value.toString()), fieldType);
    }
    Analyzer analyzer = getAnalyzer(fieldType);
    assert analyzer != null;
    MatchQueryBuilder builder = new MatchQueryBuilder(analyzer, fieldType);
    builder.setEnablePositionIncrements(this.enablePositionIncrements);
    Query query = null;
    switch(type) {
        case BOOLEAN:
            if (commonTermsCutoff == null) {
                query = builder.createBooleanQuery(field, value.toString(), occur);
            } else {
                query = builder.createCommonTermsQuery(field, value.toString(), occur, occur, commonTermsCutoff, fieldType);
            }
            break;
        case PHRASE:
            query = builder.createPhraseQuery(field, value.toString(), phraseSlop);
            break;
        case PHRASE_PREFIX:
            query = builder.createPhrasePrefixQuery(field, value.toString(), phraseSlop, maxExpansions);
            break;
        default:
            throw new IllegalStateException("No type found for [" + type + "]");
    }
    if (query == null) {
        return zeroTermsQuery();
    } else {
        return query;
    }
}

BooleanQuery. BooleanQuery is a container of Boolean clauses, that are optional, required or prohibited subqueries. You can normally add a clause to BooleanQuery making use of an API method that looks like:

public void add(Query query, boolean required, boolean prohibited)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top