7 * This source file is subject to the new BSD license that is bundled
8 * with this package in the file LICENSE.txt.
9 * It is also available through the world-wide-web at this URL:
10 * http://framework.zend.com/license/new-bsd
11 * If you did not receive a copy of the license and are unable to
12 * obtain it through the world-wide-web, please send an email
13 * to license@zend.com so we can send you a copy immediately.
16 * @package Zend_Search_Lucene
18 * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
19 * @license http://framework.zend.com/license/new-bsd New BSD License
20 * @version $Id: Wildcard.php 16971 2009-07-22 18:05:45Z mikaelkael $
24 /** Zend_Search_Lucene_Search_Query */
25 require_once 'Zend/Search/Lucene/Search/Query.php';
27 /** Zend_Search_Lucene_Search_Query_MultiTerm */
28 require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php';
33 * @package Zend_Search_Lucene
35 * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
36 * @license http://framework.zend.com/license/new-bsd New BSD License
38 class Zend_Search_Lucene_Search_Query_Wildcard extends Zend_Search_Lucene_Search_Query
43 * Field has to be fully specified or has to be null
44 * Text may contain '*' or '?' symbols
46 * @var Zend_Search_Lucene_Index_Term
54 * It's filled during the search (rewrite operation) and may be used for search result
57 * Array of Zend_Search_Lucene_Index_Term objects
61 private $_matches = null;
64 * Minimum term prefix length (number of minimum non-wildcard characters)
68 private static $_minPrefixLength = 3;
71 * Zend_Search_Lucene_Search_Query_Wildcard constructor.
73 * @param Zend_Search_Lucene_Index_Term $pattern
75 public function __construct(Zend_Search_Lucene_Index_Term $pattern)
77 $this->_pattern = $pattern;
81 * Get minimum prefix length
85 public static function getMinPrefixLength()
87 return self::$_minPrefixLength;
91 * Set minimum prefix length
93 * @param integer $minPrefixLength
95 public static function setMinPrefixLength($minPrefixLength)
97 self::$_minPrefixLength = $minPrefixLength;
103 * @param string $word
106 private static function _getPrefix($word)
108 $questionMarkPosition = strpos($word, '?');
109 $astrericPosition = strpos($word, '*');
111 if ($questionMarkPosition !== false) {
112 if ($astrericPosition !== false) {
113 return substr($word, 0, min($questionMarkPosition, $astrericPosition));
116 return substr($word, 0, $questionMarkPosition);
117 } else if ($astrericPosition !== false) {
118 return substr($word, 0, $astrericPosition);
125 * Re-write query into primitive queries in the context of specified index
127 * @param Zend_Search_Lucene_Interface $index
128 * @return Zend_Search_Lucene_Search_Query
129 * @throws Zend_Search_Lucene_Exception
131 public function rewrite(Zend_Search_Lucene_Interface $index)
133 $this->_matches = array();
135 if ($this->_pattern->field === null) {
136 // Search through all fields
137 $fields = $index->getFieldNames(true /* indexed fields list */);
139 $fields = array($this->_pattern->field);
142 $prefix = self::_getPrefix($this->_pattern->text);
143 $prefixLength = strlen($prefix);
144 $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*') , preg_quote($this->_pattern->text, '/')) . '$/';
146 if ($prefixLength < self::$_minPrefixLength) {
147 throw new Zend_Search_Lucene_Exception('At least ' . self::$_minPrefixLength . ' non-wildcard characters are required at the beginning of pattern.');
150 /** @todo check for PCRE unicode support may be performed through Zend_Environment in some future */
151 if (@preg_match('/\pL/u', 'a') == 1) {
152 // PCRE unicode support is turned on
153 // add Unicode modifier to the match expression
154 $matchExpression .= 'u';
157 $maxTerms = Zend_Search_Lucene::getTermsPerQueryLimit();
158 foreach ($fields as $field) {
159 $index->resetTermsStream();
162 $index->skipTo(new Zend_Search_Lucene_Index_Term($prefix, $field));
164 while ($index->currentTerm() !== null &&
165 $index->currentTerm()->field == $field &&
166 substr($index->currentTerm()->text, 0, $prefixLength) == $prefix) {
167 if (preg_match($matchExpression, $index->currentTerm()->text) === 1) {
168 $this->_matches[] = $index->currentTerm();
170 if ($maxTerms != 0 && count($this->_matches) > $maxTerms) {
171 throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
178 $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field));
180 while ($index->currentTerm() !== null && $index->currentTerm()->field == $field) {
181 if (preg_match($matchExpression, $index->currentTerm()->text) === 1) {
182 $this->_matches[] = $index->currentTerm();
184 if ($maxTerms != 0 && count($this->_matches) > $maxTerms) {
185 throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
193 $index->closeTermsStream();
196 if (count($this->_matches) == 0) {
197 return new Zend_Search_Lucene_Search_Query_Empty();
198 } else if (count($this->_matches) == 1) {
199 return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches));
201 $rewrittenQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
203 foreach ($this->_matches as $matchedTerm) {
204 $rewrittenQuery->addTerm($matchedTerm);
207 return $rewrittenQuery;
212 * Optimize query in the context of specified index
214 * @param Zend_Search_Lucene_Interface $index
215 * @return Zend_Search_Lucene_Search_Query
217 public function optimize(Zend_Search_Lucene_Interface $index)
219 throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
224 * Returns query pattern
226 * @return Zend_Search_Lucene_Index_Term
228 public function getPattern()
230 return $this->_pattern;
238 * @throws Zend_Search_Lucene_Exception
240 public function getQueryTerms()
242 if ($this->_matches === null) {
243 throw new Zend_Search_Lucene_Exception('Search has to be performed first to get matched terms');
246 return $this->_matches;
250 * Constructs an appropriate Weight implementation for this query.
252 * @param Zend_Search_Lucene_Interface $reader
253 * @return Zend_Search_Lucene_Search_Weight
254 * @throws Zend_Search_Lucene_Exception
256 public function createWeight(Zend_Search_Lucene_Interface $reader)
258 throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
263 * Execute query in context of index reader
264 * It also initializes necessary internal structures
266 * @param Zend_Search_Lucene_Interface $reader
267 * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
268 * @throws Zend_Search_Lucene_Exception
270 public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
272 throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
276 * Get document ids likely matching the query
278 * It's an array with document ids as keys (performance considerations)
281 * @throws Zend_Search_Lucene_Exception
283 public function matchedDocs()
285 throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
289 * Score specified document
291 * @param integer $docId
292 * @param Zend_Search_Lucene_Interface $reader
294 * @throws Zend_Search_Lucene_Exception
296 public function score($docId, Zend_Search_Lucene_Interface $reader)
298 throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
302 * Query specific matches highlighting
304 * @param Zend_Search_Lucene_Search_Highlighter_Interface $highlighter Highlighter object (also contains doc for highlighting)
306 protected function _highlightMatches(Zend_Search_Lucene_Search_Highlighter_Interface $highlighter)
310 $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*') , preg_quote($this->_pattern->text, '/')) . '$/';
311 if (@preg_match('/\pL/u', 'a') == 1) {
312 // PCRE unicode support is turned on
313 // add Unicode modifier to the match expression
314 $matchExpression .= 'u';
317 $docBody = $highlighter->getDocument()->getFieldUtf8Value('body');
318 $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($docBody, 'UTF-8');
319 foreach ($tokens as $token) {
320 if (preg_match($matchExpression, $token->getTermText()) === 1) {
321 $words[] = $token->getTermText();
325 $highlighter->highlight($words);
333 public function __toString()
335 // It's used only for query visualisation, so we don't care about characters escaping
336 if ($this->_pattern->field !== null) {
337 $query = $this->_pattern->field . ':';
342 $query .= $this->_pattern->text;
344 if ($this->getBoost() != 1) {
345 $query = $query . '^' . round($this->getBoost(), 4);