Zend_Search_Lucene-BestPractice.xml 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- Reviewed: no -->
  3. <sect1 id="zend.search.lucene.best-practice">
  4. <title>Best Practices</title>
  5. <sect2 id="zend.search.lucene.best-practice.field-names">
  6. <title>Field names</title>
  7. <para>
  8. There are no limitations for field names in <classname>Zend_Search_Lucene</classname>.
  9. </para>
  10. <para>
  11. Nevertheless it's a good idea not to use '<emphasis>id</emphasis>' and '<emphasis>score</emphasis>' names
  12. to avoid ambiguity in <code>QueryHit</code> properties names.
  13. </para>
  14. <para>
  15. The <classname>Zend_Search_Lucene_Search_QueryHit</classname> <code>id</code> and <code>score</code> properties always refer
  16. to internal Lucene document id and hit <link linkend="zend.search.lucene.searching.results-scoring">score</link>.
  17. If the indexed document has the same stored fields, you have to use the <code>getDocument()</code> method to access them:
  18. <programlisting language="php"><![CDATA[
  19. $hits = $index->find($query);
  20. foreach ($hits as $hit) {
  21. // Get 'title' document field
  22. $title = $hit->title;
  23. // Get 'contents' document field
  24. $contents = $hit->contents;
  25. // Get internal Lucene document id
  26. $id = $hit->id;
  27. // Get query hit score
  28. $score = $hit->score;
  29. // Get 'id' document field
  30. $docId = $hit->getDocument()->id;
  31. // Get 'score' document field
  32. $docId = $hit->getDocument()->score;
  33. // Another way to get 'title' document field
  34. $title = $hit->getDocument()->title;
  35. }
  36. ]]></programlisting>
  37. </para>
  38. </sect2>
  39. <sect2 id="zend.search.lucene.best-practice.indexing-performance">
  40. <title>Indexing performance</title>
  41. <para>
  42. Indexing performance is a compromise between used resources, indexing time and index quality.
  43. </para>
  44. <para>
  45. Index quality is completely determined by number of index segments.
  46. </para>
  47. <para>
  48. Each index segment is entirely independent portion of data. So indexes containing more segments need
  49. more memory and time for searching.
  50. </para>
  51. <para>
  52. Index optimization is a process of merging several segments into a new one. A fully optimized index contains
  53. only one segment.
  54. </para>
  55. <para>
  56. Full index optimization may be performed with the <code>optimize()</code> method:
  57. <programlisting language="php"><![CDATA[
  58. $index = Zend_Search_Lucene::open($indexPath);
  59. $index->optimize();
  60. ]]></programlisting>
  61. </para>
  62. <para>
  63. Index optimization works with data streams and doesn't take a lot of memory but does require processor resources and time.
  64. </para>
  65. <para>
  66. Lucene index segments are not updatable by their nature (the update operation requires the segment file
  67. to be completely rewritten). So adding new document(s) to an index always generates a new segment.
  68. This, in turn, decreases index quality.
  69. </para>
  70. <para>
  71. An index auto-optimization process is performed after each segment generation and consists of merging partial segments.
  72. </para>
  73. <para>
  74. There are three options to control the behavior of auto-optimization
  75. (see <link linkend="zend.search.lucene.index-creation.optimization">Index optimization</link> section):
  76. <itemizedlist>
  77. <listitem>
  78. <para><emphasis>MaxBufferedDocs</emphasis> is the number of documents that can be buffered in memory before a new segment is generated
  79. and written to the hard drive.</para>
  80. </listitem>
  81. <listitem>
  82. <para><emphasis>MaxMergeDocs</emphasis> is the maximum number of documents merged by auto-optimization process
  83. into a new segment.</para>
  84. </listitem>
  85. <listitem>
  86. <para><emphasis>MergeFactor</emphasis> determines how often auto-optimization is performed.</para>
  87. </listitem>
  88. </itemizedlist>
  89. <note>
  90. <para>
  91. All these options are <classname>Zend_Search_Lucene</classname> object properties- not index properties. They affect only current
  92. <classname>Zend_Search_Lucene</classname> object behavior and may vary for different scripts.
  93. </para>
  94. </note>
  95. </para>
  96. <para>
  97. <emphasis>MaxBufferedDocs</emphasis> doesn't have any effect if you index only one document per script execution. On the other hand, it's very important
  98. for batch indexing. Greater values increase indexing performance, but also require more memory.
  99. </para>
  100. <para>
  101. There is simply no way to calculate the best value for the <emphasis>MaxBufferedDocs</emphasis> parameter because it depends on average document size, the
  102. analyzer in use and allowed memory.
  103. </para>
  104. <para>
  105. A good way to find the right value is to perform several tests with the largest document you expect to be added to the index
  106. <footnote><para><code>memory_get_usage()</code> and <code>memory_get_peak_usage()</code> may be used to control
  107. memory usage.</para></footnote>. It's a best practice not to use more than a half of the allowed memory.
  108. </para>
  109. <para>
  110. <emphasis>MaxMergeDocs</emphasis> limits the segment size (in terms of documents). It therefore also limits auto-optimization time by guaranteeing
  111. that the <code>addDocument()</code> method is not executed more than a certain number of times. This is very important for interactive applications.
  112. </para>
  113. <para>
  114. Lowering the <emphasis>MaxMergeDocs</emphasis> parameter also may improve batch indexing performance. Index auto-optimization is an iterative process
  115. and is performed from bottom up. Small segments are merged into larger segment, which are in turn merged into even larger segments and
  116. so on. Full index optimization is achieved when only one large segment file remains.
  117. </para>
  118. <para>
  119. Small segments generally decrease index quality. Many small segments may also trigger
  120. the "Too many open files" error determined by OS limitations <footnote><para><classname>Zend_Search_Lucene</classname> keeps each segment file opened
  121. to improve search performance.</para></footnote>.
  122. </para>
  123. <para>
  124. in general, background index optimization should be performed for interactive indexing mode and <emphasis>MaxMergeDocs</emphasis> shouldn't be
  125. too low for batch indexing.
  126. </para>
  127. <para>
  128. <emphasis>MergeFactor</emphasis> affects auto-optimization frequency. Lower values increase the quality of unoptimized indexes. Larger values increase
  129. indexing performance, but also increase the number of merged segments. This again may trigger the "Too many open files" error.
  130. </para>
  131. <para>
  132. <emphasis>MergeFactor</emphasis> groups index segments by their size:
  133. <orderedlist>
  134. <listitem><para>Not greater than <emphasis>MaxBufferedDocs</emphasis>.</para></listitem>
  135. <listitem><para>Greater than <emphasis>MaxBufferedDocs</emphasis>, but not greater than
  136. <emphasis>MaxBufferedDocs</emphasis>*<emphasis>MergeFactor</emphasis>.</para></listitem>
  137. <listitem><para>Greater than <emphasis>MaxBufferedDocs</emphasis>*<emphasis>MergeFactor</emphasis>, but not greater than
  138. <emphasis>MaxBufferedDocs</emphasis>*<emphasis>MergeFactor</emphasis>*<emphasis>MergeFactor</emphasis>.</para></listitem>
  139. <listitem><para>...</para></listitem>
  140. </orderedlist>
  141. </para>
  142. <para>
  143. <classname>Zend_Search_Lucene</classname> checks during each <code>addDocument()</code> call to see if merging any segments may move the newly created segment
  144. into the next group. If yes, then merging is performed.
  145. </para>
  146. <para>
  147. So an index with N groups may contain <emphasis>MaxBufferedDocs</emphasis> + (N-1)*<emphasis>MergeFactor</emphasis> segments and contains at least
  148. <emphasis>MaxBufferedDocs</emphasis>*<emphasis>MergeFactor</emphasis><superscript>(N-1)</superscript> documents.
  149. </para>
  150. <para>
  151. This gives good approximation for the number of segments in the index:
  152. </para>
  153. <para>
  154. <emphasis>NumberOfSegments</emphasis> &lt;= <emphasis>MaxBufferedDocs</emphasis> + <emphasis>MergeFactor</emphasis>*log
  155. <subscript><emphasis>MergeFactor</emphasis></subscript> (<emphasis>NumberOfDocuments</emphasis>/<emphasis>MaxBufferedDocs</emphasis>)
  156. </para>
  157. <para>
  158. <emphasis>MaxBufferedDocs</emphasis> is determined by allowed memory. This allows for the appropriate merge factor to get a reasonable
  159. number of segments.
  160. </para>
  161. <para>
  162. Tuning the <emphasis>MergeFactor</emphasis> parameter is more effective for batch indexing performance than <emphasis>MaxMergeDocs</emphasis>. But it's also more course-grained.
  163. So use the estimation above for tuning <emphasis>MergeFactor</emphasis>, then play with <emphasis>MaxMergeDocs</emphasis> to get best batch indexing performance.
  164. </para>
  165. </sect2>
  166. <sect2 id="zend.search.lucene.best-practice.shutting-down">
  167. <title>Index during Shut Down</title>
  168. <para>
  169. The <classname>Zend_Search_Lucene</classname> instance performs some work at exit time if any documents were added to the index but not written to a new segment.
  170. </para>
  171. <para>
  172. It also may trigger an auto-optimization process.
  173. </para>
  174. <para>
  175. The index object is automatically closed when it, and all returned QueryHit objects, go out of scope.
  176. </para>
  177. <para>
  178. If index object is stored in global variable than it's closed only at the end of script execution<footnote><para>This also
  179. may occur if the index or QueryHit instances are referred to in some cyclical data structures, because PHP garbage collects objects
  180. with cyclic references only at the end of script execution.</para></footnote>.
  181. </para>
  182. <para>
  183. PHP exception processing is also shut down at this moment.
  184. </para>
  185. <para>
  186. It doesn't prevent normal index shutdown process, but may prevent accurate error diagnostic if any error occurs during shutdown.
  187. </para>
  188. <para>
  189. There are two ways with which you may avoid this problem.
  190. </para>
  191. <para>
  192. The first is to force going out of scope:
  193. <programlisting language="php"><![CDATA[
  194. $index = Zend_Search_Lucene::open($indexPath);
  195. ...
  196. unset($index);
  197. ]]></programlisting>
  198. </para>
  199. <para>
  200. And the second is to perform a commit operation before the end of script execution:
  201. <programlisting language="php"><![CDATA[
  202. $index = Zend_Search_Lucene::open($indexPath);
  203. $index->commit();
  204. ]]></programlisting>
  205. This possibility is also described in the "<link linkend="zend.search.lucene.advanced.static">Advanced. Using index as static property</link>"
  206. section.
  207. </para>
  208. </sect2>
  209. <sect2 id="zend.search.lucene.best-practice.unique-id">
  210. <title>Retrieving documents by unique id</title>
  211. <para>
  212. It's a common practice to store some unique document id in the index. Examples include url, path, or database id.
  213. </para>
  214. <para>
  215. <classname>Zend_Search_Lucene</classname> provides a <code>termDocs()</code> method for retrieving documents containing specified terms.
  216. </para>
  217. <para>
  218. This is more efficient than using the <code>find()</code> method:
  219. <programlisting language="php"><![CDATA[
  220. // Retrieving documents with find() method using a query string
  221. $query = $idFieldName . ':' . $docId;
  222. $hits = $index->find($query);
  223. foreach ($hits as $hit) {
  224. $title = $hit->title;
  225. $contents = $hit->contents;
  226. ...
  227. }
  228. ...
  229. // Retrieving documents with find() method using the query API
  230. $term = new Zend_Search_Lucene_Index_Term($docId, idFieldName);
  231. $query = new Zend_Search_Lucene_Search_Query_Term($term);
  232. $hits = $index->find($query);
  233. foreach ($hits as $hit) {
  234. $title = $hit->title;
  235. $contents = $hit->contents;
  236. ...
  237. }
  238. ...
  239. // Retrieving documents with termDocs() method
  240. $term = new Zend_Search_Lucene_Index_Term($docId, idFieldName);
  241. $docIds = $index->termDocs($term);
  242. foreach ($docIds as $id) {
  243. $doc = $index->getDocument($id);
  244. $title = $doc->title;
  245. $contents = $doc->contents;
  246. ...
  247. }
  248. ]]></programlisting>
  249. </para>
  250. </sect2>
  251. <sect2 id="zend.search.lucene.best-practice.memory-usage">
  252. <title>Memory Usage</title>
  253. <para>
  254. <classname>Zend_Search_Lucene</classname> is a relatively memory-intensive module.
  255. </para>
  256. <para>
  257. It uses memory to cache some information and optimize searching and indexing performance.
  258. </para>
  259. <para>
  260. The memory required differs for different modes.
  261. </para>
  262. <para>
  263. The terms dictionary index is loaded during the search. It's actually each 128<superscript>th</superscript>
  264. <footnote><para>The Lucene file format allows you to configure this number, but <classname>Zend_Search_Lucene</classname> doesn't expose this
  265. in its API. Nevertheless you still have the ability to configure this value if the index is prepared with another
  266. Lucene implementation.</para></footnote> term of the full dictionary.
  267. </para>
  268. <para>
  269. Thus memory usage is increased if you have a high number of unique terms. This may happen if you use untokenized phrases as a field values
  270. or index a large volume of non-text information.
  271. </para>
  272. <para>
  273. An unoptimized index consists of several segments. It also increases memory usage. Segments are independent, so each segment contains
  274. its own terms dictionary and terms dictionary index. If an index consists of <emphasis>N</emphasis> segments it may increase memory
  275. usage by <emphasis>N</emphasis> times in worst case. Perform index optimization to merge all segments into one to avoid such memory consumption.
  276. </para>
  277. <para>
  278. Indexing uses the same memory as searching plus memory for buffering documents. The amount of memory used may be managed with
  279. <emphasis>MaxBufferedDocs</emphasis> parameter.
  280. </para>
  281. <para>
  282. Index optimization (full or partial) uses stream-style data processing and doesn't require a lot of memory.
  283. </para>
  284. </sect2>
  285. <sect2 id="zend.search.lucene.best-practice.encoding">
  286. <title>Encoding</title>
  287. <para>
  288. <classname>Zend_Search_Lucene</classname> works with UTF-8 strings internally. So all strings returned by <classname>Zend_Search_Lucene</classname> are UTF-8 encoded.
  289. </para>
  290. <para>
  291. You shouldn't be concerned with encoding if you work with pure ASCII data, but you should be careful if this is not the case.
  292. </para>
  293. <para>
  294. Wrong encoding may cause error notices at the encoding conversion time or loss of data.
  295. </para>
  296. <para>
  297. <classname>Zend_Search_Lucene</classname> offers a wide range of encoding possibilities for indexed documents and parsed queries.
  298. </para>
  299. <para>
  300. Encoding may be explicitly specified as an optional parameter of field creation methods:
  301. <programlisting language="php"><![CDATA[
  302. $doc = new Zend_Search_Lucene_Document();
  303. $doc->addField(Zend_Search_Lucene_Field::Text('title',
  304. $title,
  305. 'iso-8859-1'));
  306. $doc->addField(Zend_Search_Lucene_Field::UnStored('contents',
  307. $contents,
  308. 'utf-8'));
  309. ]]></programlisting>
  310. This is the best way to avoid ambiguity in the encoding used.
  311. </para>
  312. <para>
  313. If optional encoding parameter is omitted, then the current locale is used. The current locale may contain character encoding data
  314. in addition to the language specification:
  315. <programlisting language="php"><![CDATA[
  316. setlocale(LC_ALL, 'fr_FR');
  317. ...
  318. setlocale(LC_ALL, 'de_DE.iso-8859-1');
  319. ...
  320. setlocale(LC_ALL, 'ru_RU.UTF-8');
  321. ...
  322. ]]></programlisting>
  323. </para>
  324. <para>
  325. The same approach is used to set query string encoding.
  326. </para>
  327. <para>
  328. If encoding is not specified, then the current locale is used to determine the encoding.
  329. </para>
  330. <para>
  331. Encoding may be passed as an optional parameter, if the query is parsed explicitly before search:
  332. <programlisting language="php"><![CDATA[
  333. $query =
  334. Zend_Search_Lucene_Search_QueryParser::parse($queryStr, 'iso-8859-5');
  335. $hits = $index->find($query);
  336. ...
  337. ]]></programlisting>
  338. </para>
  339. <para>
  340. The default encoding may also be specified with <code>setDefaultEncoding()</code> method:
  341. <programlisting language="php"><![CDATA[
  342. Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('iso-8859-1');
  343. $hits = $index->find($queryStr);
  344. ...
  345. ]]></programlisting>
  346. The empty string implies 'current locale'.
  347. </para>
  348. <para>
  349. If the correct encoding is specified it can be correctly processed by analyzer. The actual behavior depends on which analyzer is used.
  350. See the <link linkend="zend.search.lucene.charset">Character Set</link> documentation section for details.
  351. </para>
  352. </sect2>
  353. <sect2 id="zend.search.lucene.best-practice.maintenance">
  354. <title>Index maintenance</title>
  355. <para>
  356. It should be clear that <classname>Zend_Search_Lucene</classname> as well as any other Lucene implementation does not comprise a "database".
  357. </para>
  358. <para>
  359. Indexes should not be used for data storage. They do not provide partial backup/restore functionality, journaling, logging, transactions
  360. and many other features associated with database management systems.
  361. </para>
  362. <para>
  363. Nevertheless, <classname>Zend_Search_Lucene</classname> attempts to keep indexes in a consistent state at all times.
  364. </para>
  365. <para>
  366. Index backup and restoration should be performed by copying the contents of the index folder.
  367. </para>
  368. <para>
  369. If index corruption occurs for any reason, the corrupted index should be restored or completely rebuilt.
  370. </para>
  371. <para>
  372. So it's a good idea to backup large indexes and store changelogs to perform manual restoration and roll-forward operations
  373. if necessary. This practice dramatically reduces index restoration time.
  374. </para>
  375. </sect2>
  376. </sect1>