1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.search.lucene.extending">
4 <title>Extensibility</title>
6 <sect2 id="zend.search.lucene.extending.analysis">
7 <title>Text Analysis</title>
10 The <classname>Zend_Search_Lucene_Analysis_Analyzer</classname> class is used by the
11 indexer to tokenize document text fields.
15 The <methodname>Zend_Search_Lucene_Analysis_Analyzer::getDefault()</methodname> and
16 <code>Zend_Search_Lucene_Analysis_Analyzer::setDefault()</code> methods are used
17 to get and set the default analyzer.
21 You can assign your own text analyzer or choose it from the set of predefined analyzers:
22 <classname>Zend_Search_Lucene_Analysis_Analyzer_Common_Text</classname> and
23 <classname>Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive</classname>
24 (default). Both of them interpret tokens as sequences of letters.
25 <classname>Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive</classname>
26 converts all tokens to lower case.
30 To switch between analyzers:
33 <programlisting language="php"><![CDATA[
34 Zend_Search_Lucene_Analysis_Analyzer::setDefault(
35 new Zend_Search_Lucene_Analysis_Analyzer_Common_Text());
37 $index->addDocument($doc);
41 The <classname>Zend_Search_Lucene_Analysis_Analyzer_Common</classname> class is designed
42 to be an ancestor of all user defined analyzers. User should only define the
43 <methodname>reset()</methodname> and <methodname>nextToken()</methodname> methods, which
44 takes its string from the $_input member and returns tokens one by one (a
45 <constant>NULL</constant> value indicates the end of the stream).
49 The <methodname>nextToken()</methodname> method should call the
50 <methodname>normalize()</methodname> method on each token. This will allow you to use
51 token filters with your analyzer.
55 Here is an example of a custom analyzer, which accepts words with digits as terms:
57 <example id="zend.search.lucene.extending.analysis.example-1">
58 <title>Custom text Analyzer</title>
60 <programlisting language="php"><![CDATA[
62 * Here is a custom text analyser, which treats words with digits as
66 class My_Analyzer extends Zend_Search_Lucene_Analysis_Analyzer_Common
73 public function reset()
79 * Tokenization stream API
81 * Returns null at the end of stream
83 * @return Zend_Search_Lucene_Analysis_Token|null
85 public function nextToken()
87 if ($this->_input === null) {
91 while ($this->_position < strlen($this->_input)) {
93 while ($this->_position < strlen($this->_input) &&
94 !ctype_alnum( $this->_input[$this->_position] )) {
98 $termStartPosition = $this->_position;
101 while ($this->_position < strlen($this->_input) &&
102 ctype_alnum( $this->_input[$this->_position] )) {
106 // Empty token, end of stream.
107 if ($this->_position == $termStartPosition) {
111 $token = new Zend_Search_Lucene_Analysis_Token(
112 substr($this->_input,
118 $token = $this->normalize($token);
119 if ($token !== null) {
122 // Continue if token is skipped
129 Zend_Search_Lucene_Analysis_Analyzer::setDefault(
136 <sect2 id="zend.search.lucene.extending.filters">
137 <title>Tokens Filtering</title>
140 The <classname>Zend_Search_Lucene_Analysis_Analyzer_Common</classname> analyzer also
141 offers a token filtering mechanism.
145 The <classname>Zend_Search_Lucene_Analysis_TokenFilter</classname> class provides an
146 abstract interface for such filters. Your own filters should extend this class either
147 directly or indirectly.
151 Any custom filter must implement the <methodname>normalize()</methodname> method which
152 may transform input token or signal that the current token should be skipped.
156 There are three filters already defined in the analysis subpackage:
161 <classname>Zend_Search_Lucene_Analysis_TokenFilter_LowerCase</classname>
167 <classname>Zend_Search_Lucene_Analysis_TokenFilter_ShortWords</classname>
173 <classname>Zend_Search_Lucene_Analysis_TokenFilter_StopWords</classname>
180 The <code>LowerCase</code> filter is already used for
181 <classname>Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive</classname>
186 The <code>ShortWords</code> and <code>StopWords</code> filters may be used with
187 pre-defined or custom analyzers like this:
190 <programlisting language="php"><![CDATA[
191 $stopWords = array('a', 'an', 'at', 'the', 'and', 'or', 'is', 'am');
193 new Zend_Search_Lucene_Analysis_TokenFilter_StopWords($stopWords);
196 new Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive();
197 $analyzer->addFilter($stopWordsFilter);
199 Zend_Search_Lucene_Analysis_Analyzer::setDefault($analyzer);
202 <programlisting language="php"><![CDATA[
203 $shortWordsFilter = new Zend_Search_Lucene_Analysis_TokenFilter_ShortWords();
206 new Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive();
207 $analyzer->addFilter($shortWordsFilter);
209 Zend_Search_Lucene_Analysis_Analyzer::setDefault($analyzer);
213 The <classname>Zend_Search_Lucene_Analysis_TokenFilter_StopWords</classname> constructor
214 takes an array of stop-words as an input. But stop-words may be also loaded from a file:
217 <programlisting language="php"><![CDATA[
218 $stopWordsFilter = new Zend_Search_Lucene_Analysis_TokenFilter_StopWords();
219 $stopWordsFilter->loadFromFile($my_stopwords_file);
222 new Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive();
223 $analyzer->addFilter($stopWordsFilter);
225 Zend_Search_Lucene_Analysis_Analyzer::setDefault($analyzer);
229 This file should be a common text file with one word in each line. The '#' character
230 marks a line as a comment.
234 The <classname>Zend_Search_Lucene_Analysis_TokenFilter_ShortWords</classname>
235 constructor has one optional argument. This is the word length limit, set by default to
240 <sect2 id="zend.search.lucene.extending.scoring">
241 <title>Scoring Algorithms</title>
244 The score of a document <literal>d</literal> for a query <literal>q</literal>
245 is defined as follows:
249 <code>score(q,d) = sum( tf(t in d) * idf(t) * getBoost(t.field in d) *
250 lengthNorm(t.field in d) ) * coord(q,d) * queryNorm(q)</code>
254 tf(t in d) - <methodname>Zend_Search_Lucene_Search_Similarity::tf($freq)</methodname> -
255 a score factor based on the frequency of a term or phrase in a document.
259 idf(t) - <methodname>Zend_Search_Lucene_Search_Similarity::idf($input,
260 $reader)</methodname> - a score factor for a simple term with the specified index.
264 getBoost(t.field in d) - the boost factor for the term field.
268 lengthNorm($term) - the normalization value for a field given the total
269 number of terms contained in a field. This value is stored within the index.
270 These values, together with field boosts, are stored in an index and multiplied
271 into scores for hits on each field by the search code.
275 Matches in longer fields are less precise, so implementations of this method usually
276 return smaller values when numTokens is large, and larger values when numTokens is
281 coord(q,d) - <methodname>Zend_Search_Lucene_Search_Similarity::coord($overlap,
282 $maxOverlap)</methodname> - a score factor based on the fraction of all query terms
283 that a document contains.
287 The presence of a large portion of the query terms indicates a better match
288 with the query, so implementations of this method usually return larger values
289 when the ratio between these parameters is large and smaller values when
290 the ratio between them is small.
294 queryNorm(q) - the normalization value for a query given the sum of the squared weights
295 of each of the query terms. This value is then multiplied into the weight of each query
300 This does not affect ranking, but rather just attempts to make scores from different
305 The scoring algorithm can be customized by defining your own Similarity class. To do
306 this extend the <classname>Zend_Search_Lucene_Search_Similarity</classname> class as
307 defined below, then use the
308 <classname>Zend_Search_Lucene_Search_Similarity::setDefault($similarity);</classname>
309 method to set it as default.
312 <programlisting language="php"><![CDATA[
313 class MySimilarity extends Zend_Search_Lucene_Search_Similarity {
314 public function lengthNorm($fieldName, $numTerms) {
315 return 1.0/sqrt($numTerms);
318 public function queryNorm($sumOfSquaredWeights) {
319 return 1.0/sqrt($sumOfSquaredWeights);
322 public function tf($freq) {
327 * It's not used now. Computes the amount of a sloppy phrase match,
328 * based on an edit distance.
330 public function sloppyFreq($distance) {
334 public function idfFreq($docFreq, $numDocs) {
335 return log($numDocs/(float)($docFreq+1)) + 1.0;
338 public function coord($overlap, $maxOverlap) {
339 return $overlap/(float)$maxOverlap;
343 $mySimilarity = new MySimilarity();
344 Zend_Search_Lucene_Search_Similarity::setDefault($mySimilarity);
348 <sect2 id="zend.search.lucene.extending.storage">
349 <title>Storage Containers</title>
352 The abstract class <classname>Zend_Search_Lucene_Storage_Directory</classname> defines
353 directory functionality.
357 The <classname>Zend_Search_Lucene</classname> constructor uses either a string or a
358 <classname>Zend_Search_Lucene_Storage_Directory</classname> object as an input.
362 The <classname>Zend_Search_Lucene_Storage_Directory_Filesystem</classname> class
363 implements directory functionality for a file system.
367 If a string is used as an input for the <classname>Zend_Search_Lucene</classname>
368 constructor, then the index reader (<classname>Zend_Search_Lucene</classname> object)
369 treats it as a file system path and instantiates the
370 <classname>Zend_Search_Lucene_Storage_Directory_Filesystem</classname> object.
374 You can define your own directory implementation by extending the
375 <classname>Zend_Search_Lucene_Storage_Directory</classname> class.
379 <classname>Zend_Search_Lucene_Storage_Directory</classname> methods:
382 <programlisting language="php"><![CDATA[
383 abstract class Zend_Search_Lucene_Storage_Directory {
389 abstract function close();
392 * Creates a new, empty file in the directory with the given $filename.
394 * @param string $name
397 abstract function createFile($filename);
400 * Removes an existing $filename in the directory.
402 * @param string $filename
405 abstract function deleteFile($filename);
408 * Returns true if a file with the given $filename exists.
410 * @param string $filename
413 abstract function fileExists($filename);
416 * Returns the length of a $filename in the directory.
418 * @param string $filename
421 abstract function fileLength($filename);
424 * Returns the UNIX timestamp $filename was last modified.
426 * @param string $filename
429 abstract function fileModified($filename);
432 * Renames an existing file in the directory.
434 * @param string $from
438 abstract function renameFile($from, $to);
441 * Sets the modified time of $filename to now.
443 * @param string $filename
446 abstract function touchFile($filename);
449 * Returns a Zend_Search_Lucene_Storage_File object for a given
450 * $filename in the directory.
452 * @param string $filename
453 * @return Zend_Search_Lucene_Storage_File
455 abstract function getFileObject($filename);
461 The <methodname>getFileObject($filename)</methodname> method of a
462 <classname>Zend_Search_Lucene_Storage_Directory</classname> instance returns a
463 <classname>Zend_Search_Lucene_Storage_File</classname> object.
467 The <classname>Zend_Search_Lucene_Storage_File</classname> abstract class implements
468 file abstraction and index file reading primitives.
472 You must also extend <classname>Zend_Search_Lucene_Storage_File</classname> for your
473 directory implementation.
477 Only two methods of <classname>Zend_Search_Lucene_Storage_File</classname> must be
478 overridden in your implementation:
481 <programlisting language="php"><![CDATA[
482 class MyFile extends Zend_Search_Lucene_Storage_File {
484 * Sets the file position indicator and advances the file pointer.
485 * The new position, measured in bytes from the beginning of the file,
486 * is obtained by adding offset to the position specified by whence,
487 * whose values are defined as follows:
488 * SEEK_SET - Set position equal to offset bytes.
489 * SEEK_CUR - Set position to current location plus offset.
490 * SEEK_END - Set position to end-of-file plus offset. (To move to
491 * a position before the end-of-file, you need to pass a negative value
493 * Upon success, returns 0; otherwise, returns -1
495 * @param integer $offset
496 * @param integer $whence
499 public function seek($offset, $whence=SEEK_SET) {
504 * Read a $length bytes from the file and advance the file pointer.
506 * @param integer $length
509 protected function _fread($length=1) {