FileDocCategorySizeDatePackage
BooleanQuery.javaAPI DocApache Lucene 1.916830Mon Feb 20 09:20:04 GMT 2006org.apache.lucene.search

BooleanQuery

public class BooleanQuery extends Query
A Query that matches documents matching boolean combinations of other queries, e.g. {@link TermQuery}s, {@link PhraseQuery}s or other BooleanQuerys.

Fields Summary
public static int
maxClauseCount
private Vector
clauses
private boolean
disableCoord
protected int
minNrShouldMatch
private static boolean
useScorer14
Indicates whether to use good old 1.4 BooleanScorer.
Constructors Summary
public BooleanQuery()
Constructs an empty boolean query.


        
    
public BooleanQuery(boolean disableCoord)
Constructs an empty boolean query. {@link Similarity#coord(int,int)} may be disabled in scoring, as appropriate. For example, this score factor does not make sense for most automatically generated queries, like {@link WildcardQuery} and {@link FuzzyQuery}.

param
disableCoord disables {@link Similarity#coord(int,int)} in scoring.

    this.disableCoord = disableCoord;
  
Methods Summary
public voidadd(org.apache.lucene.search.Query query, org.apache.lucene.search.BooleanClause$Occur occur)
Adds a clause to a boolean query.

throws
TooManyClauses if the new number of clauses exceeds the maximum clause number
see
#getMaxClauseCount()

    add(new BooleanClause(query, occur));
  
public voidadd(org.apache.lucene.search.BooleanClause clause)
Adds a clause to a boolean query.

throws
TooManyClauses if the new number of clauses exceeds the maximum clause number
see
#getMaxClauseCount()

    if (clauses.size() >= maxClauseCount)
      throw new TooManyClauses();

    clauses.addElement(clause);
  
public voidadd(org.apache.lucene.search.Query query, boolean required, boolean prohibited)
Adds a clause to a boolean query. Clauses may be:
  • required which means that documents which do not match this sub-query will not match the boolean query;
  • prohibited which means that documents which do match this sub-query will not match the boolean query; or
  • neither, in which case matched documents are neither prohibited from nor required to match the sub-query. However, a document must match at least 1 sub-query to match the boolean query.
It is an error to specify a clause as both required and prohibited.

deprecated
use {@link #add(Query, BooleanClause.Occur)} instead:
  • For add(query, true, false) use add(query, BooleanClause.Occur.MUST)
  • For add(query, false, false) use add(query, BooleanClause.Occur.SHOULD)
  • For add(query, false, true) use add(query, BooleanClause.Occur.MUST_NOT)

    add(new BooleanClause(query, required, prohibited));
  
public java.lang.Objectclone()

    BooleanQuery clone = (BooleanQuery)super.clone();
    clone.clauses = (Vector)this.clauses.clone();
    return clone;
  
protected org.apache.lucene.search.WeightcreateWeight(org.apache.lucene.search.Searcher searcher)


    if (0 < minNrShouldMatch) {
      // :TODO: should we throw an exception if getUseScorer14 ?
      return new BooleanWeight2(searcher);
    }

    return getUseScorer14() ? (Weight) new BooleanWeight(searcher)
                            : (Weight) new BooleanWeight2(searcher);
  
public booleanequals(java.lang.Object o)
Returns true iff o is equal to this.

    if (!(o instanceof BooleanQuery))
      return false;
    BooleanQuery other = (BooleanQuery)o;
    return (this.getBoost() == other.getBoost())
        && this.clauses.equals(other.clauses)
        && this.getMinimumNumberShouldMatch() == other.getMinimumNumberShouldMatch();
  
public voidextractTerms(java.util.Set terms)

      for (Iterator i = clauses.iterator(); i.hasNext();) {
          BooleanClause clause = (BooleanClause) i.next();
          clause.getQuery().extractTerms(terms);
        }
  
public org.apache.lucene.search.BooleanClause[]getClauses()
Returns the set of clauses in this query.

    return (BooleanClause[])clauses.toArray(new BooleanClause[0]);
  
public static intgetMaxClauseCount()
Return the maximum number of clauses permitted, 1024 by default. Attempts to add more than the permitted number of clauses cause {@link TooManyClauses} to be thrown.

see
#setMaxClauseCount(int)


                                     
        

                                 
       return maxClauseCount; 
public intgetMinimumNumberShouldMatch()
Gets the minimum number of the optional BooleanClauses which must be satisifed.


                 
     
    return minNrShouldMatch;
  
public org.apache.lucene.search.SimilaritygetSimilarity(org.apache.lucene.search.Searcher searcher)

    Similarity result = super.getSimilarity(searcher);
    if (disableCoord) {                           // disable coord as requested
      result = new SimilarityDelegator(result) {
          public float coord(int overlap, int maxOverlap) {
            return 1.0f;
          }
        };
    }
    return result;
  
public static booleangetUseScorer14()

    return useScorer14;
  
public inthashCode()
Returns a hash code value for this object.

    return Float.floatToIntBits(getBoost()) ^ clauses.hashCode()
           + getMinimumNumberShouldMatch();
  
public booleanisCoordDisabled()
Returns true iff {@link Similarity#coord(int,int)} is disabled in scoring for this query instance.

see
#BooleanQuery(boolean)

 return disableCoord; 
public org.apache.lucene.search.Queryrewrite(org.apache.lucene.index.IndexReader reader)

    if (clauses.size() == 1) {                    // optimize 1-clause queries
      BooleanClause c = (BooleanClause)clauses.elementAt(0);
      if (!c.isProhibited()) {			  // just return clause

        Query query = c.getQuery().rewrite(reader);    // rewrite first

        if (getBoost() != 1.0f) {                 // incorporate boost
          if (query == c.getQuery())                   // if rewrite was no-op
            query = (Query)query.clone();         // then clone before boost
          query.setBoost(getBoost() * query.getBoost());
        }

        return query;
      }
    }

    BooleanQuery clone = null;                    // recursively rewrite
    for (int i = 0 ; i < clauses.size(); i++) {
      BooleanClause c = (BooleanClause)clauses.elementAt(i);
      Query query = c.getQuery().rewrite(reader);
      if (query != c.getQuery()) {                     // clause rewrote: must clone
        if (clone == null)
          clone = (BooleanQuery)this.clone();
        clone.clauses.setElementAt
          (new BooleanClause(query, c.getOccur()), i);
      }
    }
    if (clone != null) {
      return clone;                               // some clauses rewrote
    } else
      return this;                                // no clauses rewrote
  
public static voidsetMaxClauseCount(int maxClauseCount)
Set the maximum number of clauses permitted per BooleanQuery. Default value is 1024.

TermQuery clauses are generated from for example prefix queries and fuzzy queries. Each TermQuery needs some buffer space during search, so this parameter indirectly controls the maximum buffer requirements for query search.

When this parameter becomes a bottleneck for a Query one can use a Filter. For example instead of a {@link RangeQuery} one can use a {@link RangeFilter}.

Normally the buffers are allocated by the JVM. When using for example {@link org.apache.lucene.store.MMapDirectory} the buffering is left to the operating system.

    if (maxClauseCount < 1)
      throw new IllegalArgumentException("maxClauseCount must be >= 1");
    BooleanQuery.maxClauseCount = maxClauseCount;
  
public voidsetMinimumNumberShouldMatch(int min)
Specifies a minimum number of the optional BooleanClauses which must be satisifed.

By default no optional clauses are neccessary for a match (unless there are no required clauses). If this method is used, then the specified numebr of clauses is required.

Use of this method is totally independant of specifying that any specific clauses are required (or prohibited). This number will only be compared against the number of matching optional clauses.

EXPERT NOTE: Using this method will force the use of BooleanWeight2, regardless of wether setUseScorer14(true) has been called.

param
min the number of optional clauses that must match
see
#setUseScorer14

    this.minNrShouldMatch = min;
  
public static voidsetUseScorer14(boolean use14)


       
    useScorer14 = use14;
  
public java.lang.StringtoString(java.lang.String field)
Prints a user-readable version of this query.

    StringBuffer buffer = new StringBuffer();
    boolean needParens=(getBoost() != 1.0) || (getMinimumNumberShouldMatch()>0) ;
    if (needParens) {
      buffer.append("(");
    }

    for (int i = 0 ; i < clauses.size(); i++) {
      BooleanClause c = (BooleanClause)clauses.elementAt(i);
      if (c.isProhibited())
        buffer.append("-");
      else if (c.isRequired())
        buffer.append("+");

      Query subQuery = c.getQuery();
      if (subQuery instanceof BooleanQuery) {	  // wrap sub-bools in parens
        buffer.append("(");
        buffer.append(c.getQuery().toString(field));
        buffer.append(")");
      } else
        buffer.append(c.getQuery().toString(field));

      if (i != clauses.size()-1)
        buffer.append(" ");
    }

    if (needParens) {
      buffer.append(")");
    }

    if (getMinimumNumberShouldMatch()>0) {
      buffer.append('~");
      buffer.append(getMinimumNumberShouldMatch());
    }

    if (getBoost() != 1.0f)
    {
      buffer.append(ToStringUtils.boost(getBoost()));
    }

    return buffer.toString();