PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Boolean Query

Boolean queries allow to construct query using other queries and boolean operators.

Each subquery in a set can be defined as required, prohibited, or optional.

  • required means that documents not matching this subquery will not match the query;

  • prohibited means that documents matching this subquery will not match the query;

  • optional, in which case matched documents are neither prohibited from, nor required to, match the subquery. A document must match at least 1 subquery, however, to match the query.

If optional subqueries are added to a query with required subqueries, both queries will have the same result set but the optional subqueries may affect the score of the matched documents.

Both search methods can be used for boolean queries.

Query string:

+(word1 word2 word3) (author:word4 author:word5) -(word6)
  • '+' is used to define a required subquery.

  • '-' is used to define a prohibited subquery.

  • 'field:' prefix is used to indicate a document field for a search. If it's omitted, then all fields are searched.

or

Query construction by API:

<?php
$query 
= new Zend_Search_Lucene_Search_Query_Boolean();

$subquery1 = new Zend_Search_Lucene_Search_Query_MultiTerm();
$subquery1->addTerm(new Zend_Search_Lucene_Index_Term('word1'));
$subquery1->addTerm(new Zend_Search_Lucene_Index_Term('word2'));
$subquery1->addTerm(new Zend_Search_Lucene_Index_Term('word3'));

$subquery2 = new Zend_Search_Lucene_Search_Query_MultiTerm();
$subquery2->addTerm(new Zend_Search_Lucene_Index_Term('word4''author'));
$subquery2->addTerm(new Zend_Search_Lucene_Index_Term('word5''author'));

$term6 = new Zend_Search_Lucene_Index_Term('word6');
$subquery3 = new Zend_Search_Lucene_Search_Query_Term($term6);

$query->addSubquery($subquery1true  /* required */);
$query->addSubquery($subquery2null  /* optional */);
$query->addSubquery($subquery3false /* prohibited */);

$hits  $index->find($query);

It's also possible to specify subqueries list within Boolean query constructor:

<?php
...
$subqueries = array($subquery1$subquery2$subquery3);
$signs = array(truenullfalse);

$query = new Zend_Search_Lucene_Search_Query_Boolean($subqueries$signs);

$hits  $index->find($query);

The $signs array contains information about the subquery type:

  • TRUE is used to define required subquery.

  • FALSE is used to define prohibited subquery.

  • NULL is used to define a subquery that is neither required nor prohibited.

Each query which uses boolean operators can be rewritten using signs notation and constructed using API. For example:

word1 AND (word2 AND word3 AND NOT word4) OR word5

is equivalent to

(+(word1) +(+word2 +word3 -word4)) (word5)

Zend Framework