Example usage for org.apache.lucene.search BooleanQuery getMinimumNumberShouldMatch

List of usage examples for org.apache.lucene.search BooleanQuery getMinimumNumberShouldMatch

Introduction

In this page you can find the example usage for org.apache.lucene.search BooleanQuery getMinimumNumberShouldMatch.

Prototype

public int getMinimumNumberShouldMatch() 

Source Link

Document

Gets the minimum number of the optional BooleanClauses which must be satisfied.

Usage

From source file:uk.co.flax.luwak.QueryDecomposer.java

License:Apache License

/**
 * Decompose a {@link org.apache.lucene.search.BooleanQuery}
 * @param q the boolean query/*from   w ww. j av a2s.com*/
 * @return a collection of subqueries
 */
public Collection<Query> decomposeBoolean(BooleanQuery q) {
    if (q.getMinimumNumberShouldMatch() > 1)
        return listOf(q);

    List<Query> subqueries = new LinkedList<>();
    List<Query> exclusions = new LinkedList<>();
    List<Query> mandatory = new LinkedList<>();

    float parentBoost = q.getBoost();

    for (BooleanClause clause : q) {
        if (clause.getOccur() == BooleanClause.Occur.MUST)
            mandatory.add(clause.getQuery());
        else if (clause.getOccur() == BooleanClause.Occur.MUST_NOT)
            exclusions.add(clause.getQuery());
        else {
            for (Query subQuery : decompose(clause.getQuery())) {
                subqueries.add(boost(subQuery, parentBoost));
            }
        }
    }

    // More than one MUST clause, or a single MUST clause with disjunctions
    if (mandatory.size() > 1 || (mandatory.size() == 1 && subqueries.size() > 0))
        return listOf(q);

    // If we only have a single MUST clause and no SHOULD clauses, then we can
    // decompose the MUST clause instead
    if (mandatory.size() == 1) {
        for (Query subQuery : decompose(mandatory.get(0))) {
            subqueries.add(boost(subQuery, parentBoost));
        }
    }

    if (exclusions.size() == 0)
        return subqueries;

    // If there are exclusions, then we need to add them to all the decomposed
    // queries
    List<Query> rewrittenSubqueries = new ArrayList<>(subqueries.size());
    for (Query subquery : subqueries) {
        BooleanQuery.Builder bq = new BooleanQuery.Builder();
        bq.add(subquery, BooleanClause.Occur.MUST);
        for (Query ex : exclusions) {
            bq.add(ex, BooleanClause.Occur.MUST_NOT);
        }
        rewrittenSubqueries.add(bq.build());
    }
    return rewrittenSubqueries;
}