Zend_Search_Lucene-Searching.xml 21 KB

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