Zend_Search_Lucene-Searching.xml 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. </para>
  96. <programlisting language="php"><![CDATA[
  97. $userQuery = Zend_Search_Lucene_Search_QueryParser::parse($queryStr);
  98. $pathTerm = new Zend_Search_Lucene_Index_Term(
  99. '/data/doc_dir/' . $filename, 'path'
  100. );
  101. $pathQuery = new Zend_Search_Lucene_Search_Query_Term($pathTerm);
  102. $query = new Zend_Search_Lucene_Search_Query_Boolean();
  103. $query->addSubquery($userQuery, true /* required */);
  104. $query->addSubquery($pathQuery, true /* required */);
  105. $hits = $index->find($query);
  106. ]]></programlisting>
  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. </para>
  111. <programlisting language="php"><![CDATA[
  112. $userQuery = Zend_Search_Lucene_Search_QueryParser::parse($queryStr,
  113. 'iso-8859-5');
  114. ]]></programlisting>
  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. </para>
  123. <programlisting language="php"><![CDATA[
  124. Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('iso-8859-5');
  125. ...
  126. $userQuery = Zend_Search_Lucene_Search_QueryParser::parse($queryStr);
  127. ]]></programlisting>
  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. </para>
  206. <programlisting language="php"><![CDATA[
  207. $currentResultSetLimit = Zend_Search_Lucene::getResultSetLimit();
  208. Zend_Search_Lucene::setResultSetLimit($newLimit);
  209. ]]></programlisting>
  210. <para>
  211. The default value of 0 means 'no limit'.
  212. </para>
  213. <para>
  214. It doesn't give the 'best N' results, but only the 'first N'
  215. <footnote>
  216. <para>
  217. Returned hits are still ordered by score or by the specified order, if given.
  218. </para>
  219. </footnote>.
  220. </para>
  221. </sect2>
  222. <sect2 id="zend.search.lucene.searching.results-scoring">
  223. <title>Results Scoring</title>
  224. <para>
  225. <classname>Zend_Search_Lucene</classname> uses the same scoring algorithms as Java
  226. Lucene. All hits in the search result are ordered by score by default. Hits with greater
  227. score come first, and documents having higher scores should match the query more
  228. precisely than documents having lower scores.
  229. </para>
  230. <para>
  231. Roughly speaking, search hits that contain the searched term or phrase more frequently
  232. will have a higher score.
  233. </para>
  234. <para>
  235. A hit's score can be retrieved by accessing the <code>score</code> property of the hit:
  236. </para>
  237. <programlisting language="php"><![CDATA[
  238. $hits = $index->find($query);
  239. foreach ($hits as $hit) {
  240. echo $hit->id;
  241. echo $hit->score;
  242. }
  243. ]]></programlisting>
  244. <para>
  245. The <classname>Zend_Search_Lucene_Search_Similarity</classname> class is used to
  246. calculate the score for each hit. See <link
  247. linkend="zend.search.lucene.extending.scoring">Extensibility. Scoring
  248. Algorithms</link> section for details.
  249. </para>
  250. </sect2>
  251. <sect2 id="zend.search.lucene.searching.sorting">
  252. <title>Search Result Sorting</title>
  253. <para>
  254. By default, the search results are ordered by score. The programmer can change this
  255. behavior by setting a sort field (or a list of fields), sort type and sort order
  256. parameters.
  257. </para>
  258. <para>
  259. <code>$index->find()</code> call may take several optional parameters:
  260. </para>
  261. <programlisting language="php"><![CDATA[
  262. $index->find($query [, $sortField [, $sortType [, $sortOrder]]]
  263. [, $sortField2 [, $sortType [, $sortOrder]]]
  264. ...);
  265. ]]></programlisting>
  266. <para>
  267. A name of stored field by which to sort result should be passed as the
  268. <varname>$sortField</varname> parameter.
  269. </para>
  270. <para>
  271. <varname>$sortType</varname> may be omitted or take the following enumerated values:
  272. <constant>SORT_REGULAR</constant> (compare items normally- default value),
  273. <constant>SORT_NUMERIC</constant> (compare items numerically),
  274. <constant>SORT_STRING</constant> (compare items as strings).
  275. </para>
  276. <para>
  277. <varname>$sortOrder</varname> may be omitted or take the following enumerated values:
  278. <constant>SORT_ASC</constant> (sort in ascending order- default value),
  279. <constant>SORT_DESC</constant> (sort in descending order).
  280. </para>
  281. <para>
  282. Examples:
  283. </para>
  284. <programlisting language="php"><![CDATA[
  285. $index->find($query, 'quantity', SORT_NUMERIC, SORT_DESC);
  286. ]]></programlisting>
  287. <programlisting language="php"><![CDATA[
  288. $index->find($query, 'fname', SORT_STRING, 'lname', SORT_STRING);
  289. ]]></programlisting>
  290. <programlisting language="php"><![CDATA[
  291. $index->find($query, 'name', SORT_STRING, 'quantity', SORT_NUMERIC, SORT_DESC);
  292. ]]></programlisting>
  293. <para>
  294. Please use caution when using a non-default search order; the query needs to retrieve
  295. documents completely from an index, which may dramatically reduce search performance.
  296. </para>
  297. </sect2>
  298. <sect2 id="zend.search.lucene.searching.highlighting">
  299. <title>Search Results Highlighting</title>
  300. <para>
  301. <classname>Zend_Search_Lucene</classname> provides two options for search results
  302. highlighting.
  303. </para>
  304. <para>
  305. The first one is utilizing <classname>Zend_Search_Lucene_Document_Html</classname> class
  306. (see <link linkend="zend.search.lucene.index-creation.html-documents">HTML documents
  307. section</link> for details) using the following methods:
  308. </para>
  309. <programlisting language="php"><![CDATA[
  310. /**
  311. * Highlight text with specified color
  312. *
  313. * @param string|array $words
  314. * @param string $colour
  315. * @return string
  316. */
  317. public function highlight($words, $colour = '#66ffff');
  318. ]]></programlisting>
  319. <programlisting language="php"><![CDATA[
  320. /**
  321. * Highlight text using specified View helper or callback function.
  322. *
  323. * @param string|array $words Words to highlight. Words could be organized
  324. using the array or string.
  325. * @param callback $callback Callback method, used to transform
  326. (highlighting) text.
  327. * @param array $params Array of additionall callback parameters passed
  328. through into it (first non-optional parameter
  329. is an HTML fragment for highlighting)
  330. * @return string
  331. * @throws Zend_Search_Lucene_Exception
  332. */
  333. public function highlightExtended($words, $callback, $params = array())
  334. ]]></programlisting>
  335. <para>
  336. To customize highlighting behavior use <methodname>highlightExtended()</methodname>
  337. method with specified callback, which takes one or more parameters
  338. <footnote>
  339. <para>
  340. The first is an <acronym>HTML</acronym> fragment for highlighting and others are
  341. callback behavior dependent. Returned value is a highlighted
  342. <acronym>HTML</acronym> fragment.
  343. </para>
  344. </footnote>
  345. , or extend <classname>Zend_Search_Lucene_Document_Html</classname> class and redefine
  346. <methodname>applyColour($stringToHighlight, $colour)</methodname> method used as a
  347. default highlighting callback.
  348. <footnote>
  349. <para>
  350. In both cases returned <acronym>HTML</acronym> is automatically transformed into
  351. valid <acronym>XHTML</acronym>.
  352. </para>
  353. </footnote>
  354. </para>
  355. <para>
  356. <link linkend="zend.view.helpers">View helpers</link> also can be used as callbacks in
  357. context of view script:
  358. </para>
  359. <programlisting language="php"><![CDATA[
  360. $doc->highlightExtended('word1 word2 word3...', array($this, 'myViewHelper'));
  361. ]]></programlisting>
  362. <para>
  363. The result of highlighting operation is retrieved by
  364. <code>Zend_Search_Lucene_Document_Html->getHTML()</code> method.
  365. </para>
  366. <note>
  367. <para>
  368. Highlighting is performed in terms of current analyzer. So all forms of the word(s)
  369. recognized by analyzer are highlighted.
  370. </para>
  371. <para>
  372. E.g. if current analyzer is case insensitive and we request to highlight 'text'
  373. word, then 'text', 'Text', 'TEXT' and other case combinations will be highlighted.
  374. </para>
  375. <para>
  376. In the same way, if current analyzer supports stemming and we request to highlight
  377. 'indexed', then 'index', 'indexing', 'indices' and other word forms will be
  378. highlighted.
  379. </para>
  380. <para>
  381. On the other hand, if word is skipped by current analyzer (e.g. if short words
  382. filter is applied to the analyzer), then nothing will be highlighted.
  383. </para>
  384. </note>
  385. <para>
  386. The second option is to use
  387. <code>Zend_Search_Lucene_Search_Query->highlightMatches(string $inputHTML[,
  388. $defaultEncoding = 'UTF-8'[,
  389. Zend_Search_Lucene_Search_Highlighter_Interface $highlighter]])</code> method:
  390. </para>
  391. <programlisting language="php"><![CDATA[
  392. $query = Zend_Search_Lucene_Search_QueryParser::parse($queryStr);
  393. $highlightedHTML = $query->highlightMatches($sourceHTML);
  394. ]]></programlisting>
  395. <para>
  396. Optional second parameter is a default <acronym>HTML</acronym> document encoding. It's
  397. used if encoding is not specified using Content-type HTTP-EQUIV meta tag.
  398. </para>
  399. <para>
  400. Optional third parameter is a highlighter object which has to implement
  401. <classname>Zend_Search_Lucene_Search_Highlighter_Interface</classname> interface:
  402. </para>
  403. <programlisting language="php"><![CDATA[
  404. interface Zend_Search_Lucene_Search_Highlighter_Interface
  405. {
  406. /**
  407. * Set document for highlighting.
  408. *
  409. * @param Zend_Search_Lucene_Document_Html $document
  410. */
  411. public function setDocument(Zend_Search_Lucene_Document_Html $document);
  412. /**
  413. * Get document for highlighting.
  414. *
  415. * @return Zend_Search_Lucene_Document_Html $document
  416. */
  417. public function getDocument();
  418. /**
  419. * Highlight specified words (method is invoked once per subquery)
  420. *
  421. * @param string|array $words Words to highlight. They could be
  422. organized using the array or string.
  423. */
  424. public function highlight($words);
  425. }
  426. ]]></programlisting>
  427. <para>
  428. Where <classname>Zend_Search_Lucene_Document_Html</classname> object is an object
  429. constructed from the source <acronym>HTML</acronym> provided to the
  430. <classname>Zend_Search_Lucene_Search_Query->highlightMatches()</classname> method.
  431. </para>
  432. <para>
  433. If <varname>$highlighter</varname> parameter is omitted, then
  434. <classname>Zend_Search_Lucene_Search_Highlighter_Default</classname> object is
  435. instantiated and used.
  436. </para>
  437. <para>
  438. Highlighter <methodname>highlight()</methodname> method is invoked once per subquery, so
  439. it has an ability to differentiate highlighting for them.
  440. </para>
  441. <para>
  442. Actually, default highlighter does this walking through predefined color table. So you
  443. can implement your own highlighter or just extend the default and redefine color table.
  444. </para>
  445. <para>
  446. <code>Zend_Search_Lucene_Search_Query->htmlFragmentHighlightMatches()</code> has similar
  447. behavior. The only difference is that it takes as an input and returns
  448. <acronym>HTML</acronym> fragment without &lt;>HTML>, &lt;HEAD>, &lt;BODY> tags.
  449. Nevertheless, fragment is automatically transformed to valid <acronym>XHTML</acronym>.
  450. </para>
  451. </sect2>
  452. </sect1>