1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.search.lucene.searching">
4 <title>Searching an Index</title>
6 <sect2 id="zend.search.lucene.searching.query_building">
7 <title>Building Queries</title>
10 There are two ways to search the index. The first method uses
11 query parser to construct a query from a string. The second is
12 to programmatically create your own queries through the
13 <classname>Zend_Search_Lucene</classname> <acronym>API</acronym>.
17 Before choosing to use the provided query parser, please consider
23 If you are programmatically creating a query string and then parsing
24 it with the query parser then you should consider building your queries
25 directly with the query <acronym>API</acronym>. Generally speaking, the
26 query parser is designed for human-entered text, not for program-generated
33 Untokenized fields are best added directly to queries and not through
34 the query parser. If a field's values are generated programmatically
35 by the application, then the query clauses for this field should also
36 be constructed programmatically.
37 An analyzer, which the query parser uses, is designed to convert
38 human-entered text to terms. Program-generated values, like dates,
39 keywords, etc., should be added with the query <acronym>API</acronym>.
45 In a query form, fields that are general text should use the query parser.
46 All others, such as date ranges, keywords, etc., are better added directly
47 through the query <acronym>API</acronym>. A field with a limited set of
48 values that can be specified with a pull-down menu should not be added to a
49 query string that is subsequently parsed but instead should be added as a
56 Boolean queries allow the programmer to logically combine two or more
57 queries into new one. Thus it's the best way to add additional criteria to a
58 search defined by a query string.
65 Both ways use the same <acronym>API</acronym> method to search through the index:
68 <programlisting language="php"><![CDATA[
69 $index = Zend_Search_Lucene::open('/data/my_index');
75 The <methodname>Zend_Search_Lucene::find()</methodname> method determines the input type
76 automatically and uses the query parser to construct an appropriate
77 <classname>Zend_Search_Lucene_Search_Query</classname> object from an input of type
82 It is important to note that the query parser uses the standard analyzer to tokenize
83 separate parts of query string. Thus all transformations which are applied to indexed
84 text are also applied to query strings.
88 The standard analyzer may transform the query string to lower case for
89 case-insensitivity, remove stop-words, and stem among other transformations.
93 The <acronym>API</acronym> method doesn't transform or filter input terms in any way.
94 It's therefore more suitable for computer generated or untokenized fields.
97 <sect3 id="zend.search.lucene.searching.query_building.parsing">
98 <title>Query Parsing</title>
101 <methodname>Zend_Search_Lucene_Search_QueryParser::parse()</methodname> method may
102 be used to parse query strings into query objects.
106 This query object may be used in query construction <acronym>API</acronym> methods
107 to combine user entered queries with programmatically generated queries.
111 Actually, in some cases it's the only way to search for values within untokenized
115 <programlisting language="php"><![CDATA[
116 $userQuery = Zend_Search_Lucene_Search_QueryParser::parse($queryStr);
118 $pathTerm = new Zend_Search_Lucene_Index_Term(
119 '/data/doc_dir/' . $filename, 'path'
121 $pathQuery = new Zend_Search_Lucene_Search_Query_Term($pathTerm);
123 $query = new Zend_Search_Lucene_Search_Query_Boolean();
124 $query->addSubquery($userQuery, true /* required */);
125 $query->addSubquery($pathQuery, true /* required */);
127 $hits = $index->find($query);
131 <methodname>Zend_Search_Lucene_Search_QueryParser::parse()</methodname> method also
132 takes an optional encoding parameter, which can specify query string encoding:
135 <programlisting language="php"><![CDATA[
136 $userQuery = Zend_Search_Lucene_Search_QueryParser::parse($queryStr,
141 If the encoding parameter is omitted, then current locale is used.
145 It's also possible to specify the default query string encoding with
146 <methodname>Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding()</methodname>
150 <programlisting language="php"><![CDATA[
151 Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('iso-8859-5');
153 $userQuery = Zend_Search_Lucene_Search_QueryParser::parse($queryStr);
157 <methodname>Zend_Search_Lucene_Search_QueryParser::getDefaultEncoding()</methodname>
158 returns the current default query string encoding (the empty string means "current
164 <sect2 id="zend.search.lucene.searching.results">
165 <title>Search Results</title>
168 The search result is an array of
169 <classname>Zend_Search_Lucene_Search_QueryHit</classname> objects. Each of these has two
170 properties: <code>$hit->id</code> is a document number within the index and
171 <code>$hit->score</code> is a score of the hit in a search result. The results are
172 ordered by score (descending from highest score).
176 The <classname>Zend_Search_Lucene_Search_QueryHit</classname> object also exposes each
177 field of the <classname>Zend_Search_Lucene_Document</classname> found in the search as a
178 property of the hit. In the following example, a hit is returned with two fields from
179 the corresponding document: title and author.
182 <programlisting language="php"><![CDATA[
183 $index = Zend_Search_Lucene::open('/data/my_index');
185 $hits = $index->find($query);
187 foreach ($hits as $hit) {
195 Stored fields are always returned in UTF-8 encoding.
199 Optionally, the original <classname>Zend_Search_Lucene_Document</classname> object can
200 be returned from the <classname>Zend_Search_Lucene_Search_QueryHit</classname>.
201 You can retrieve stored parts of the document by using the
202 <methodname>getDocument()</methodname> method of the index object and then get them by
203 <methodname>getFieldValue()</methodname> method:
206 <programlisting language="php"><![CDATA[
207 $index = Zend_Search_Lucene::open('/data/my_index');
209 $hits = $index->find($query);
210 foreach ($hits as $hit) {
211 // return Zend_Search_Lucene_Document object for this hit
212 echo $document = $hit->getDocument();
214 // return a Zend_Search_Lucene_Field object
215 // from the Zend_Search_Lucene_Document
216 echo $document->getField('title');
218 // return the string value of the Zend_Search_Lucene_Field object
219 echo $document->getFieldValue('title');
221 // same as getFieldValue()
222 echo $document->title;
227 The fields available from the <classname>Zend_Search_Lucene_Document</classname> object
228 are determined at the time of indexing. The document fields are either indexed, or
229 index and stored, in the document by the indexing application
230 (e.g. LuceneIndexCreation.jar).
234 Note that the document identity ('path' in our example) is also stored
235 in the index and must be retrieved from it.
239 <sect2 id="zend.search.lucene.searching.results-limiting">
240 <title>Limiting the Result Set</title>
243 The most computationally expensive part of searching is score calculation. It may take
244 several seconds for large result sets (tens of thousands of hits).
248 <classname>Zend_Search_Lucene</classname> gives the possibility to limit result set size
249 with <methodname>getResultSetLimit()</methodname> and
250 <methodname>setResultSetLimit()</methodname> methods:
253 <programlisting language="php"><![CDATA[
254 $currentResultSetLimit = Zend_Search_Lucene::getResultSetLimit();
256 Zend_Search_Lucene::setResultSetLimit($newLimit);
260 The default value of 0 means 'no limit'.
264 It doesn't give the 'best N' results, but only the 'first N'
268 Returned hits are still ordered by score or by the specified order, if given.
274 <sect2 id="zend.search.lucene.searching.results-scoring">
275 <title>Results Scoring</title>
278 <classname>Zend_Search_Lucene</classname> uses the same scoring algorithms as Java
279 Lucene. All hits in the search result are ordered by score by default. Hits with greater
280 score come first, and documents having higher scores should match the query more
281 precisely than documents having lower scores.
285 Roughly speaking, search hits that contain the searched term or phrase more frequently
286 will have a higher score.
290 A hit's score can be retrieved by accessing the <code>score</code> property of the hit:
293 <programlisting language="php"><![CDATA[
294 $hits = $index->find($query);
296 foreach ($hits as $hit) {
303 The <classname>Zend_Search_Lucene_Search_Similarity</classname> class is used to
304 calculate the score for each hit. See <link
305 linkend="zend.search.lucene.extending.scoring">Extensibility. Scoring
306 Algorithms</link> section for details.
310 <sect2 id="zend.search.lucene.searching.sorting">
311 <title>Search Result Sorting</title>
314 By default, the search results are ordered by score. The programmer can change this
315 behavior by setting a sort field (or a list of fields), sort type and sort order
320 <code>$index->find()</code> call may take several optional parameters:
323 <programlisting language="php"><![CDATA[
324 $index->find($query [, $sortField [, $sortType [, $sortOrder]]]
325 [, $sortField2 [, $sortType [, $sortOrder]]]
330 A name of stored field by which to sort result should be passed as the
331 <varname>$sortField</varname> parameter.
335 <varname>$sortType</varname> may be omitted or take the following enumerated values:
336 <constant>SORT_REGULAR</constant> (compare items normally- default value),
337 <constant>SORT_NUMERIC</constant> (compare items numerically),
338 <constant>SORT_STRING</constant> (compare items as strings).
342 <varname>$sortOrder</varname> may be omitted or take the following enumerated values:
343 <constant>SORT_ASC</constant> (sort in ascending order- default value),
344 <constant>SORT_DESC</constant> (sort in descending order).
351 <programlisting language="php"><![CDATA[
352 $index->find($query, 'quantity', SORT_NUMERIC, SORT_DESC);
355 <programlisting language="php"><![CDATA[
356 $index->find($query, 'fname', SORT_STRING, 'lname', SORT_STRING);
359 <programlisting language="php"><![CDATA[
360 $index->find($query, 'name', SORT_STRING, 'quantity', SORT_NUMERIC, SORT_DESC);
364 Please use caution when using a non-default search order; the query needs to retrieve
365 documents completely from an index, which may dramatically reduce search performance.
369 <sect2 id="zend.search.lucene.searching.highlighting">
370 <title>Search Results Highlighting</title>
373 <classname>Zend_Search_Lucene</classname> provides two options for search results
378 The first one is utilizing <classname>Zend_Search_Lucene_Document_Html</classname> class
379 (see <link linkend="zend.search.lucene.index-creation.html-documents">HTML documents
380 section</link> for details) using the following methods:
383 <programlisting language="php"><![CDATA[
385 * Highlight text with specified color
387 * @param string|array $words
388 * @param string $colour
391 public function highlight($words, $colour = '#66ffff');
394 <programlisting language="php"><![CDATA[
396 * Highlight text using specified View helper or callback function.
398 * @param string|array $words Words to highlight. Words could be organized
399 using the array or string.
400 * @param callback $callback Callback method, used to transform
402 * @param array $params Array of additionall callback parameters passed
403 through into it (first non-optional parameter
404 is an HTML fragment for highlighting)
406 * @throws Zend_Search_Lucene_Exception
408 public function highlightExtended($words, $callback, $params = array())
412 To customize highlighting behavior use <methodname>highlightExtended()</methodname>
413 method with specified callback, which takes one or more parameters
417 The first is an <acronym>HTML</acronym> fragment for highlighting and others are
418 callback behavior dependent. Returned value is a highlighted
419 <acronym>HTML</acronym> fragment.
422 , or extend <classname>Zend_Search_Lucene_Document_Html</classname> class and redefine
423 <methodname>applyColour($stringToHighlight, $colour)</methodname> method used as a
424 default highlighting callback.
428 In both cases returned <acronym>HTML</acronym> is automatically transformed into
429 valid <acronym>XHTML</acronym>.
435 <link linkend="zend.view.helpers">View helpers</link> also can be used as callbacks in
436 context of view script:
439 <programlisting language="php"><![CDATA[
440 $doc->highlightExtended('word1 word2 word3...', array($this, 'myViewHelper'));
444 The result of highlighting operation is retrieved by
445 <code>Zend_Search_Lucene_Document_Html->getHTML()</code> method.
450 Highlighting is performed in terms of current analyzer. So all forms of the word(s)
451 recognized by analyzer are highlighted.
455 E.g. if current analyzer is case insensitive and we request to highlight 'text'
456 word, then 'text', 'Text', 'TEXT' and other case combinations will be highlighted.
460 In the same way, if current analyzer supports stemming and we request to highlight
461 'indexed', then 'index', 'indexing', 'indices' and other word forms will be
466 On the other hand, if word is skipped by current analyzer (e.g. if short words
467 filter is applied to the analyzer), then nothing will be highlighted.
472 The second option is to use
473 <code>Zend_Search_Lucene_Search_Query->highlightMatches(string $inputHTML[,
474 $defaultEncoding = 'UTF-8'[,
475 Zend_Search_Lucene_Search_Highlighter_Interface $highlighter]])</code> method:
478 <programlisting language="php"><![CDATA[
479 $query = Zend_Search_Lucene_Search_QueryParser::parse($queryStr);
480 $highlightedHTML = $query->highlightMatches($sourceHTML);
484 Optional second parameter is a default <acronym>HTML</acronym> document encoding. It's
485 used if encoding is not specified using Content-type HTTP-EQUIV meta tag.
489 Optional third parameter is a highlighter object which has to implement
490 <classname>Zend_Search_Lucene_Search_Highlighter_Interface</classname> interface:
493 <programlisting language="php"><![CDATA[
494 interface Zend_Search_Lucene_Search_Highlighter_Interface
497 * Set document for highlighting.
499 * @param Zend_Search_Lucene_Document_Html $document
501 public function setDocument(Zend_Search_Lucene_Document_Html $document);
504 * Get document for highlighting.
506 * @return Zend_Search_Lucene_Document_Html $document
508 public function getDocument();
511 * Highlight specified words (method is invoked once per subquery)
513 * @param string|array $words Words to highlight. They could be
514 organized using the array or string.
516 public function highlight($words);
521 Where <classname>Zend_Search_Lucene_Document_Html</classname> object is an object
522 constructed from the source <acronym>HTML</acronym> provided to the
523 <classname>Zend_Search_Lucene_Search_Query->highlightMatches()</classname> method.
527 If <varname>$highlighter</varname> parameter is omitted, then
528 <classname>Zend_Search_Lucene_Search_Highlighter_Default</classname> object is
529 instantiated and used.
533 Highlighter <methodname>highlight()</methodname> method is invoked once per subquery, so
534 it has an ability to differentiate highlighting for them.
538 Actually, default highlighter does this walking through predefined color table. So you
539 can implement your own highlighter or just extend the default and redefine color table.
543 <code>Zend_Search_Lucene_Search_Query->htmlFragmentHighlightMatches()</code> has similar
544 behavior. The only difference is that it takes as an input and returns
545 <acronym>HTML</acronym> fragment without <>HTML>, <HEAD>, <BODY> tags.
546 Nevertheless, fragment is automatically transformed to valid <acronym>XHTML</acronym>.