Zend_Search_Lucene-Searching.xml 21 KB

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