Zend_Search_Lucene-Searching.xml 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- Reviewed: no -->
  3. <sect1 id="zend.search.lucene.searching">
  4. <title>Searching an Index</title>
  5. <sect2 id="zend.search.lucene.searching.query_building">
  6. <title>Building Queries</title>
  7. <para>
  8. There are two ways to search the index. The first method uses
  9. query parser to construct a query from a string. The second is
  10. to programmatically create your own queries through the <classname>Zend_Search_Lucene</classname> API.
  11. </para>
  12. <para>
  13. Before choosing to use the provided query parser, please consider
  14. the following:
  15. <orderedlist>
  16. <listitem>
  17. <para>
  18. If you are programmatically creating a query string and then parsing
  19. it with the query parser then you should consider building
  20. your queries directly with the query API. Generally speaking, the query
  21. parser is designed for human-entered text, not for program-generated text.
  22. </para>
  23. </listitem>
  24. <listitem>
  25. <para>
  26. Untokenized fields are best added directly to queries and not through
  27. the query parser. If a field's values are generated programmatically
  28. by the application, then the query clauses for this field should also
  29. be constructed programmatically.
  30. An analyzer, which the query parser uses, is designed to convert
  31. human-entered text to terms. Program-generated values, like dates,
  32. keywords, etc., should be added with the query API.
  33. </para>
  34. </listitem>
  35. <listitem>
  36. <para>
  37. In a query form, fields that are general text should use the query parser.
  38. All others, such as date ranges, keywords, etc., are better added directly
  39. through the query API. A field with a limited set of values that can be
  40. specified with a pull-down menu should not be added to a query string
  41. that is subsequently parsed but instead should be added as a TermQuery clause.
  42. </para>
  43. </listitem>
  44. <listitem>
  45. <para>
  46. Boolean queries allow the programmer to logically combine two or more queries into new one.
  47. Thus it's the best way to add additional criteria to a search defined by
  48. a query string.
  49. </para>
  50. </listitem>
  51. </orderedlist>
  52. </para>
  53. <para>
  54. Both ways use the same API method to search through the index:
  55. </para>
  56. <programlisting language="php"><![CDATA[
  57. $index = Zend_Search_Lucene::open('/data/my_index');
  58. $index->find($query);
  59. ]]></programlisting>
  60. <para>
  61. The <classname>Zend_Search_Lucene::find()</classname> method determines the input type automatically and
  62. uses the query parser to construct an appropriate <classname>Zend_Search_Lucene_Search_Query</classname> object
  63. from an input of type string.
  64. </para>
  65. <para>
  66. It is important to note that the query parser uses the standard analyzer to tokenize separate parts of query string.
  67. Thus all transformations which are applied to indexed text are also applied to query strings.
  68. </para>
  69. <para>
  70. The standard analyzer may transform the query string to lower case for case-insensitivity, remove stop-words, and stem among other transformations.
  71. </para>
  72. <para>
  73. The API method doesn't transform or filter input terms in any way. It's therefore more suitable for
  74. computer generated or untokenized fields.
  75. </para>
  76. <sect3 id="zend.search.lucene.searching.query_building.parsing">
  77. <title>Query Parsing</title>
  78. <para>
  79. <classname>Zend_Search_Lucene_Search_QueryParser::parse()</classname> method may be used to parse query strings
  80. into query objects.
  81. </para>
  82. <para>
  83. This query object may be used in query construction API methods to combine user entered queries with
  84. programmatically generated queries.
  85. </para>
  86. <para>
  87. Actually, in some cases it's the only way to search for values within untokenized fields:
  88. <programlisting language="php"><![CDATA[
  89. $userQuery = Zend_Search_Lucene_Search_QueryParser::parse($queryStr);
  90. $pathTerm = new Zend_Search_Lucene_Index_Term(
  91. '/data/doc_dir/' . $filename, 'path'
  92. );
  93. $pathQuery = new Zend_Search_Lucene_Search_Query_Term($pathTerm);
  94. $query = new Zend_Search_Lucene_Search_Query_Boolean();
  95. $query->addSubquery($userQuery, true /* required */);
  96. $query->addSubquery($pathQuery, true /* required */);
  97. $hits = $index->find($query);
  98. ]]></programlisting>
  99. </para>
  100. <para>
  101. <classname>Zend_Search_Lucene_Search_QueryParser::parse()</classname> method also takes an optional encoding parameter,
  102. which can specify query string encoding:
  103. <programlisting language="php"><![CDATA[
  104. $userQuery = Zend_Search_Lucene_Search_QueryParser::parse($queryStr,
  105. 'iso-8859-5');
  106. ]]></programlisting>
  107. </para>
  108. <para>
  109. If the encoding parameter is omitted, then current locale is used.
  110. </para>
  111. <para>
  112. It's also possible to specify the default query string encoding with
  113. <classname>Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding()</classname> method:
  114. <programlisting language="php"><![CDATA[
  115. Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('iso-8859-5');
  116. ...
  117. $userQuery = Zend_Search_Lucene_Search_QueryParser::parse($queryStr);
  118. ]]></programlisting>
  119. </para>
  120. <para>
  121. <classname>Zend_Search_Lucene_Search_QueryParser::getDefaultEncoding()</classname> returns the current default query
  122. string encoding (the empty string means "current locale").
  123. </para>
  124. </sect3>
  125. </sect2>
  126. <sect2 id="zend.search.lucene.searching.results">
  127. <title>Search Results</title>
  128. <para>
  129. The search result is an array of <classname>Zend_Search_Lucene_Search_QueryHit</classname> objects. Each of these has
  130. two properties: <code>$hit->document</code> is a document number within
  131. the index and <code>$hit->score</code> is a score of the hit in
  132. a search result. The results are ordered by score (descending from highest score).
  133. </para>
  134. <para>
  135. The <classname>Zend_Search_Lucene_Search_QueryHit</classname> object also exposes each field of the <classname>Zend_Search_Lucene_Document</classname> found in the search
  136. as a property of the hit. In the following example, a hit is returned with two fields from the corresponding document: title and author.
  137. </para>
  138. <programlisting language="php"><![CDATA[
  139. $index = Zend_Search_Lucene::open('/data/my_index');
  140. $hits = $index->find($query);
  141. foreach ($hits as $hit) {
  142. echo $hit->score;
  143. echo $hit->title;
  144. echo $hit->author;
  145. }
  146. ]]></programlisting>
  147. <para>
  148. Stored fields are always returned in UTF-8 encoding.
  149. </para>
  150. <para>
  151. Optionally, the original <classname>Zend_Search_Lucene_Document</classname> object can be returned from the
  152. <classname>Zend_Search_Lucene_Search_QueryHit</classname>.
  153. You can retrieve stored parts of the document by using the <code>getDocument()</code>
  154. method of the index object and then get them by
  155. <code>getFieldValue()</code> method:
  156. </para>
  157. <programlisting language="php"><![CDATA[
  158. $index = Zend_Search_Lucene::open('/data/my_index');
  159. $hits = $index->find($query);
  160. foreach ($hits as $hit) {
  161. // return Zend_Search_Lucene_Document object for this hit
  162. echo $document = $hit->getDocument();
  163. // return a Zend_Search_Lucene_Field object
  164. // from the Zend_Search_Lucene_Document
  165. echo $document->getField('title');
  166. // return the string value of the Zend_Search_Lucene_Field object
  167. echo $document->getFieldValue('title');
  168. // same as getFieldValue()
  169. echo $document->title;
  170. }
  171. ]]></programlisting>
  172. <para>
  173. The fields available from the <classname>Zend_Search_Lucene_Document</classname> object are determined at
  174. the time of indexing. The document fields are either indexed, or
  175. index and stored, in the document by the indexing application
  176. (e.g. LuceneIndexCreation.jar).
  177. </para>
  178. <para>
  179. Note that the document identity ('path' in our example) is also stored
  180. in the index and must be retrieved from it.
  181. </para>
  182. </sect2>
  183. <sect2 id="zend.search.lucene.searching.results-limiting">
  184. <title>Limiting the Result Set</title>
  185. <para>
  186. The most computationally expensive part of searching is score calculation. It may take several seconds for large result sets (tens of thousands of hits).
  187. </para>
  188. <para>
  189. <classname>Zend_Search_Lucene</classname> gives the possibility to limit result set size with <code>getResultSetLimit()</code> and
  190. <code>setResultSetLimit()</code> methods:
  191. <programlisting language="php"><![CDATA[
  192. $currentResultSetLimit = Zend_Search_Lucene::getResultSetLimit();
  193. Zend_Search_Lucene::setResultSetLimit($newLimit);
  194. ]]></programlisting>
  195. The default value of 0 means 'no limit'.
  196. </para>
  197. <para>
  198. It doesn't give the 'best N' results, but only the 'first N'<footnote><para>Returned hits are still ordered by score or by the the specified order, if given.</para></footnote>.
  199. </para>
  200. </sect2>
  201. <sect2 id="zend.search.lucene.searching.results-scoring">
  202. <title>Results Scoring</title>
  203. <para>
  204. <classname>Zend_Search_Lucene</classname> uses the same scoring algorithms as Java Lucene.
  205. All hits in the search result are ordered by score by default. Hits with greater score come first, and
  206. documents having higher scores should match the query more precisely than documents having lower scores.
  207. </para>
  208. <para>
  209. Roughly speaking, search hits that contain the searched term or phrase more frequently
  210. will have a higher score.
  211. </para>
  212. <para>
  213. A hit's score can be retrieved by accessing the <code>score</code> property of the hit:
  214. </para>
  215. <programlisting language="php"><![CDATA[
  216. $hits = $index->find($query);
  217. foreach ($hits as $hit) {
  218. echo $hit->id;
  219. echo $hit->score;
  220. }
  221. ]]></programlisting>
  222. <para>
  223. The <classname>Zend_Search_Lucene_Search_Similarity</classname> class is used to calculate the score for each hit.
  224. See <link linkend="zend.search.lucene.extending.scoring">Extensibility. Scoring Algorithms</link> section for details.
  225. </para>
  226. </sect2>
  227. <sect2 id="zend.search.lucene.searching.sorting">
  228. <title>Search Result Sorting</title>
  229. <para>
  230. By default, the search results are ordered by score. The programmer can change this behavior by setting a sort field (or a list of fields), sort type
  231. and sort order parameters.
  232. </para>
  233. <para>
  234. <code>$index->find()</code> call may take several optional parameters:
  235. <programlisting language="php"><![CDATA[
  236. $index->find($query [, $sortField [, $sortType [, $sortOrder]]]
  237. [, $sortField2 [, $sortType [, $sortOrder]]]
  238. ...);
  239. ]]></programlisting>
  240. </para>
  241. <para>
  242. A name of stored field by which to sort result should be passed as the <code>$sortField</code> parameter.
  243. </para>
  244. <para>
  245. <code>$sortType</code> may be omitted or take the following enumerated values:
  246. <code>SORT_REGULAR</code> (compare items normally- default value),
  247. <code>SORT_NUMERIC</code> (compare items numerically),
  248. <code>SORT_STRING</code> (compare items as strings).
  249. </para>
  250. <para>
  251. <code>$sortOrder</code> may be omitted or take the following enumerated values:
  252. <code>SORT_ASC</code> (sort in ascending order- default value),
  253. <code>SORT_DESC</code> (sort in descending order).
  254. </para>
  255. <para>
  256. Examples:
  257. <programlisting language="php"><![CDATA[
  258. $index->find($query, 'quantity', SORT_NUMERIC, SORT_DESC);
  259. ]]></programlisting>
  260. <programlisting language="php"><![CDATA[
  261. $index->find($query, 'fname', SORT_STRING, 'lname', SORT_STRING);
  262. ]]></programlisting>
  263. <programlisting language="php"><![CDATA[
  264. $index->find($query, 'name', SORT_STRING, 'quantity', SORT_NUMERIC, SORT_DESC);
  265. ]]></programlisting>
  266. </para>
  267. <para>
  268. Please use caution when using a non-default search order;
  269. the query needs to retrieve documents completely from an index, which may dramatically reduce search performance.
  270. </para>
  271. </sect2>
  272. <sect2 id="zend.search.lucene.searching.highlighting">
  273. <title>Search Results Highlighting</title>
  274. <para>
  275. Zend_Search_Lucene provides two options for search results highlighting.
  276. </para>
  277. <para>
  278. The first one is utilizing <classname>Zend_Search_Lucene_Document_Html</classname> class
  279. (see <link linkend="zend.search.lucene.index-creation.html-documents">HTML documents section</link> for details)
  280. using the following methods:
  281. <programlisting language="php"><![CDATA[
  282. /**
  283. * Highlight text with specified color
  284. *
  285. * @param string|array $words
  286. * @param string $colour
  287. * @return string
  288. */
  289. public function highlight($words, $colour = '#66ffff');
  290. ]]></programlisting>
  291. <programlisting language="php"><![CDATA[
  292. /**
  293. * Highlight text using specified View helper or callback function.
  294. *
  295. * @param string|array $words Words to highlight. Words could be organized using the array or string.
  296. * @param callback $callback Callback method, used to transform (highlighting) text.
  297. * @param array $params Array of additionall callback parameters passed through into it
  298. * (first non-optional parameter is an HTML fragment for highlighting)
  299. * @return string
  300. * @throws Zend_Search_Lucene_Exception
  301. */
  302. public function highlightExtended($words, $callback, $params = array())
  303. ]]></programlisting>
  304. </para>
  305. <para>
  306. To customize highlighting behavior use <code>highlightExtended()</code> method with specified callback, which takes
  307. one or more parameters<footnote><para>The first is an HTML fragment for highlighting and others are callback behavior
  308. dependent. Returned value is a highlighted HTML fragment.</para></footnote>, or extend
  309. <classname>Zend_Search_Lucene_Document_Html</classname> class and redefine <code>applyColour($stringToHighlight, $colour)</code>
  310. method used as a default highlighting callback.
  311. <footnote>
  312. <para>
  313. In both cases returned HTML is automatically transformed into valid XHTML.
  314. </para>
  315. </footnote>
  316. </para>
  317. <para>
  318. <link linkend="zend.view.helpers">View helpers</link> also can be used as callbacks in context of view script:
  319. <programlisting language="php"><![CDATA[
  320. $doc->highlightExtended('word1 word2 word3...', array($this, 'myViewHelper'));
  321. ]]></programlisting>
  322. </para>
  323. <para>
  324. The result of highlighting operation is retrieved by <code>Zend_Search_Lucene_Document_Html->getHTML()</code> method.
  325. </para>
  326. <note>
  327. <para>
  328. Highlighting is performed in terms of current analyzer. So all forms of the word(s) recognized by analyzer
  329. are highlighted.
  330. </para>
  331. <para>
  332. E.g. if current analyzer is case insensitive and we request to highlight 'text' word, then 'text', 'Text', 'TEXT'
  333. and other case combinations will be highlighted.
  334. </para>
  335. <para>
  336. In the same way, if current analyzer supports stemming and we request to highlight 'indexed', then 'index',
  337. 'indexing', 'indices' and other word forms will be highlighted.
  338. </para>
  339. <para>
  340. On the other hand, if word is skipped by corrent analyzer (e.g. if short words filter is applied to the analyzer),
  341. then nothing will be highlighted.
  342. </para>
  343. </note>
  344. <para>
  345. The second option is to use
  346. <code>Zend_Search_Lucene_Search_Query->highlightMatches(string $inputHTML[, $defaultEncoding = 'UTF-8'[, Zend_Search_Lucene_Search_Highlighter_Interface $highlighter]])</code>
  347. method:
  348. <programlisting language="php"><![CDATA[
  349. $query = Zend_Search_Lucene_Search_QueryParser::parse($queryStr);
  350. $highlightedHTML = $query->highlightMatches($sourceHTML);
  351. ]]></programlisting>
  352. </para>
  353. <para>
  354. Optional second parameter is a default HTML document encoding. It's used if encoding is not specified using
  355. Content-type HTTP-EQUIV meta tag.
  356. </para>
  357. <para>
  358. Optional third parameter is a highlighter object which has to implement
  359. <code>Zend_Search_Lucene_Search_Highlighter_Interface</code> interface:
  360. <programlisting language="php"><![CDATA[
  361. interface Zend_Search_Lucene_Search_Highlighter_Interface
  362. {
  363. /**
  364. * Set document for highlighting.
  365. *
  366. * @param Zend_Search_Lucene_Document_Html $document
  367. */
  368. public function setDocument(Zend_Search_Lucene_Document_Html $document);
  369. /**
  370. * Get document for highlighting.
  371. *
  372. * @return Zend_Search_Lucene_Document_Html $document
  373. */
  374. public function getDocument();
  375. /**
  376. * Highlight specified words (method is invoked once per subquery)
  377. *
  378. * @param string|array $words Words to highlight. They could be organized using the array or string.
  379. */
  380. public function highlight($words);
  381. }
  382. ]]></programlisting>
  383. Where <classname>Zend_Search_Lucene_Document_Html</classname> object is an object constructed from the source HTML
  384. provided to the <classname>Zend_Search_Lucene_Search_Query->highlightMatches()</classname> method.
  385. </para>
  386. <para>
  387. If <code>$highlighter</code> parameter is omitted, then <classname>Zend_Search_Lucene_Search_Highlighter_Default</classname>
  388. object is instantiated and used.
  389. </para>
  390. <para>
  391. Highlighter <code>highlight()</code> method is invoked once per subquery, so it has an ability to differentiate
  392. highlighting for them.
  393. </para>
  394. <para>
  395. Actually, default highlighter does this walking through predefined color table. So you can implement
  396. your own highlighter or just extend the default and redefine color table.
  397. </para>
  398. <para>
  399. <code>Zend_Search_Lucene_Search_Query->htmlFragmentHighlightMatches()</code> has similar behavior. The only differenece
  400. is that it takes as an input and returns HTML fragment without &lt;>HTML>, &lt;HEAD>, &lt;BODY> tags.
  401. Nevertheless, fragment is automatically transformed to valid XHTML.
  402. </para>
  403. </sect2>
  404. </sect1>