summaryrefslogtreecommitdiff
path: root/demos/quickstart/protected/index/Zend/Search/Lucene/Index/SegmentWriter.php
blob: f90d6ed3c53b28950a3c022d3535d13644975f7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to version 1.0 of the Zend Framework
 * license, that is bundled with this package in the file LICENSE, and
 * is available through the world-wide-web at the following URL:
 * http://www.zend.com/license/framework/1_0.txt. If you did not receive
 * a copy of the Zend Framework license and are unable to obtain it
 * through the world-wide-web, please send a note to license@zend.com
 * so we can mail you a copy immediately.
 *
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2006 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://www.zend.com/license/framework/1_0.txt Zend Framework License version 1.0
 */


/** Zend_Search_Lucene_Exception */
require_once 'Zend/Search/Lucene/Exception.php';

/** Zend_Search_Lucene_Analysis_Analyzer */
require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';

/** Zend_Search_Lucene_Index_SegmentInfo */
require_once 'Zend/Search/Lucene/Index/SegmentInfo.php';


/**
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2006 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://www.zend.com/license/framework/1_0.txt Zend Framework License version 1.0
 */
class Zend_Search_Lucene_Index_SegmentWriter
{
    /**
     * Expert: The fraction of terms in the "dictionary" which should be stored
     * in RAM.  Smaller values use more memory, but make searching slightly
     * faster, while larger values use less memory and make searching slightly
     * slower.  Searching is typically not dominated by dictionary lookup, so
     * tweaking this is rarely useful.
     *
     * @var integer
     */
    static public $indexInterval = 128;

    /** Expert: The fraction of TermDocs entries stored in skip tables.
     * Larger values result in smaller indexes, greater acceleration, but fewer
     * accelerable cases, while smaller values result in bigger indexes,
     * less acceleration and more
     * accelerable cases. More detailed experiments would be useful here.
     *
     * 0x0x7FFFFFFF indicates that we don't use skip data
     * Default value is 16
     *
     * @var integer
     */
    static public $skipInterval = 0x7FFFFFFF;

    /**
     * Number of docs in a segment
     *
     * @var integer
     */
    private $_docCount;

    /**
     * Segment name
     *
     * @var string
     */
    private $_name;

    /**
     * File system adapter.
     *
     * @var Zend_Search_Lucene_Storage_Directory
     */
    private $_directory;

    /**
     * List of the index files.
     * Used for automatic compound file generation
     *
     * @var unknown_type
     */
    private $_files;

    /**
     * Term Dictionary
     * Array of the Zend_Search_Lucene_Index_Term objects
     * Corresponding Zend_Search_Lucene_Index_TermInfo object stored in the $_termDictionaryInfos
     *
     * @var array
     */
    private $_termDictionary;

    /**
     * Documents, which contain the term
     *
     * @var array
     */
    private $_termDocs;

    /**
     * Segment fields. Array of Zend_Search_Lucene_Index_FieldInfo objects for this segment
     *
     * @var array
     */
    private $_fields;

    /**
     * Normalization factors.
     * An array fieldName => normVector
     * normVector is a binary string.
     * Each byte corresponds to an indexed document in a segment and
     * encodes normalization factor (float value, encoded by
     * Zend_Search_Lucene_Search_Similarity::encodeNorm())
     *
     * @var array
     */
    private $_norms;


    /**
     * '.fdx'  file - Stored Fields, the field index.
     *
     * @var Zend_Search_Lucene_Storage_File
     */
    private $_fdxFile;

    /**
     * '.fdx'  file - Stored Fields, the field data.
     *
     * @var Zend_Search_Lucene_Storage_File
     */
    private $_fdtFile;


    /**
     * Object constructor.
     *
     * @param Zend_Search_Lucene_Storage_Directory $directory
     * @param string $name
     */
    public function __construct($directory, $name)
    {
        $this->_directory = $directory;
        $this->_name      = $name;
        $this->_docCount  = 0;

        $this->_fields   = array();
        $this->_termDocs = array();
        $this->_files    = array();
        $this->_norms    = array();

        $this->_fdxFile = null;
        $this->_fdtFile = null;
    }


    /**
     * Add field to the segment
     *
     * @param Zend_Search_Lucene_Field $field
     */
    private function _addFieldInfo(Zend_Search_Lucene_Field $field)
    {
        if (!isset($this->_fields[$field->name])) {
            $this->_fields[$field->name] =
                                new Zend_Search_Lucene_Index_FieldInfo($field->name,
                                                                       $field->isIndexed,
                                                                       count($this->_fields),
                                                                       $field->storeTermVector);
        } else {
            $this->_fields[$field->name]->isIndexed       |= $field->isIndexed;
            $this->_fields[$field->name]->storeTermVector |= $field->storeTermVector;
        }
    }


    /**
     * Adds a document to this segment.
     *
     * @param Zend_Search_Lucene_Document $document
     * @throws Zend_Search_Lucene_Exception
     */
    public function addDocument(Zend_Search_Lucene_Document $document)
    {
        $storedFields = array();

        foreach ($document->getFieldNames() as $fieldName) {
            $field = $document->getField($fieldName);
            $this->_addFieldInfo($field);

            if ($field->storeTermVector) {
                /**
                 * @todo term vector storing support
                 */
                throw new Zend_Search_Lucene_Exception('Store term vector functionality is not supported yet.');
            }

            if ($field->isIndexed) {
                if ($field->isTokenized) {
                    $tokenList = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($field->stringValue);
                } else {
                    $tokenList = array();
                    $tokenList[] = new Zend_Search_Lucene_Analysis_Token($field->stringValue, 0, strlen($field->stringValue));
                }

                $position = 0;
                foreach ($tokenList as $token) {
                    $term = new Zend_Search_Lucene_Index_Term($token->getTermText(), $field->name);
                    $termKey = $term->key();

                    if (!isset($this->_termDictionary[$termKey])) {
                        // New term
                        $this->_termDictionary[$termKey] = $term;
                        $this->_termDocs[$termKey] = array();
                        $this->_termDocs[$termKey][$this->_docCount] = array();
                    } else if (!isset($this->_termDocs[$termKey][$this->_docCount])) {
                        // Existing term, but new term entry
                        $this->_termDocs[$termKey][$this->_docCount] = array();
                    }
                    $position += $token->getPositionIncrement();
                    $this->_termDocs[$termKey][$this->_docCount][] = $position;
                }
            }

            if ($field->isStored) {
                $storedFields[] = $field;
            }
        }

        if (count($storedFields) != 0) {
            if (!isset($this->_fdxFile)) {
                $this->_fdxFile = $this->_directory->createFile($this->_name . '.fdx');
                $this->_fdtFile = $this->_directory->createFile($this->_name . '.fdt');

                $this->_files[] = $this->_name . '.fdx';
                $this->_files[] = $this->_name . '.fdt';
            }

            $this->_fdxFile->writeLong($this->_fdtFile->tell());

            $this->_fdtFile->writeVInt(count($storedFields));
            foreach ($storedFields as $field) {
                $this->_fdtFile->writeVInt($this->_fields[$field->name]->number);
                $this->_fdtFile->writeByte($field->isTokenized ? 0x01 : 0x00 |
                                           $field->isBinary ?    0x02 : 0x00 |
                                           0x00 /* 0x04 - third bit, compressed (ZLIB) */ );
                if ($field->isBinary) {
                    $this->_fdtFile->writeVInt(strlen($field->stringValue));
                    $this->_fdtFile->writeBytes($field->stringValue);
                } else {
                    $this->_fdtFile->writeString($field->stringValue);
                }
            }
        }

        $this->_docCount++;
    }


    /**
     * Dump Field Info (.fnm) segment file
     */
    private function _dumpFNM()
    {
        $fnmFile = $this->_directory->createFile($this->_name . '.fnm');
        $fnmFile->writeVInt(count($this->_fields));

        foreach ($this->_fields as $field) {
            $fnmFile->writeString($field->name);
            $fnmFile->writeByte(($field->isIndexed       ? 0x01 : 0x00) |
                                ($field->storeTermVector ? 0x02 : 0x00) |
// not supported yet            0x04 /* term positions are stored with the term vectors */ |
// not supported yet            0x08 /* term offsets are stored with the term vectors */   |
/* not supported yet */         0x10 /* norms are omitted for the indexed field */
                               );
        }

        $this->_files[] = $this->_name . '.fnm';
    }


    /**
     * Dump Term Dictionary segment file entry.
     * Used to write entry to .tis or .tii files
     *
     * @param Zend_Search_Lucene_Storage_File $dicFile
     * @param Zend_Search_Lucene_Index_Term $prevTerm
     * @param Zend_Search_Lucene_Index_Term $term
     * @param Zend_Search_Lucene_Index_TermInfo $prevTermInfo
     * @param Zend_Search_Lucene_Index_TermInfo $termInfo
     */
    private function _dumpTermDictEntry(Zend_Search_Lucene_Storage_File $dicFile,
                                        &$prevTerm,     Zend_Search_Lucene_Index_Term     $term,
                                        &$prevTermInfo, Zend_Search_Lucene_Index_TermInfo $termInfo)
    {
        if (isset($prevTerm) && $prevTerm->field == $term->field) {
            $prefixLength = 0;
            while ($prefixLength < strlen($prevTerm->text) &&
                   $prefixLength < strlen($term->text) &&
                   $prevTerm->text{$prefixLength} == $term->text{$prefixLength}
                  ) {
                $prefixLength++;
            }
            // Write preffix length
            $dicFile->writeVInt($prefixLength);
            // Write suffix
            $dicFile->writeString( substr($term->text, $prefixLength) );
        } else {
            // Write preffix length
            $dicFile->writeVInt(0);
            // Write suffix
            $dicFile->writeString($term->text);
        }
        // Write field number
        $dicFile->writeVInt($term->field);
        // DocFreq (the count of documents which contain the term)
        $dicFile->writeVInt($termInfo->docFreq);

        $prevTerm = $term;

        if (!isset($prevTermInfo)) {
            // Write FreqDelta
            $dicFile->writeVInt($termInfo->freqPointer);
            // Write ProxDelta
            $dicFile->writeVInt($termInfo->proxPointer);
        } else {
            // Write FreqDelta
            $dicFile->writeVInt($termInfo->freqPointer - $prevTermInfo->freqPointer);
            // Write ProxDelta
            $dicFile->writeVInt($termInfo->proxPointer - $prevTermInfo->proxPointer);
        }
        // Write SkipOffset - it's not 0 when $termInfo->docFreq > self::$skipInterval
        if ($termInfo->skipOffset != 0) {
            $dicFile->writeVInt($termInfo->skipOffset);
        }

        $prevTermInfo = $termInfo;
    }

    /**
     * Dump Term Dictionary (.tis) and Term Dictionary Index (.tii) segment files
     */
    private function _dumpDictionary()
    {
        $tisFile = $this->_directory->createFile($this->_name . '.tis');
        $tisFile->writeInt((int)0xFFFFFFFE);
        $tisFile->writeLong(count($this->_termDictionary));
        $tisFile->writeInt(self::$indexInterval);
        $tisFile->writeInt(self::$skipInterval);

        $tiiFile = $this->_directory->createFile($this->_name . '.tii');
        $tiiFile->writeInt((int)0xFFFFFFFE);
        $tiiFile->writeLong((int)((count($this->_termDictionary) - 1)/self::$indexInterval) + 1);
        $tiiFile->writeInt(self::$indexInterval);
        $tiiFile->writeInt(self::$skipInterval);

        $frqFile = $this->_directory->createFile($this->_name . '.frq');
        $prxFile = $this->_directory->createFile($this->_name . '.prx');

        $termKeys = array_keys($this->_termDictionary);
        sort($termKeys, SORT_STRING);

        $termCount = 0;

        $prevTerm     = null;
        $prevTermInfo = null;
        $prevIndexTerm     = null;
        $prevIndexTermInfo = null;
        $prevIndexPosition = 0;

        foreach ($termKeys as $termId) {
            $freqPointer = $frqFile->tell();
            $proxPointer = $prxFile->tell();

            $prevDoc = 0;
            foreach ($this->_termDocs[$termId] as $docId => $termPositions) {
                $docDelta = ($docId - $prevDoc)*2;
                $prevDoc = $docId;
                if (count($termPositions) > 1) {
                    $frqFile->writeVInt($docDelta);
                    $frqFile->writeVInt(count($termPositions));
                } else {
                    $frqFile->writeVInt($docDelta + 1);
                }

                $prevPosition = 0;
                foreach ($termPositions as $position) {
                    $prxFile->writeVInt($position - $prevPosition);
                    $prevPosition = $position;
                }
            }

            if (count($this->_termDocs[$termId]) >= self::$skipInterval) {
                /**
                 * @todo Write Skip Data to a freq file.
                 * It's not used now, but must be implemented to be compatible with Lucene
                 */
                $skipOffset = $frqFile->tell() - $freqPointer;
            } else {
                $skipOffset = 0;
            }

            $term = new Zend_Search_Lucene_Index_Term($this->_termDictionary[$termId]->text,
                                                      $this->_fields[$this->_termDictionary[$termId]->field]->number);
            $termInfo = new Zend_Search_Lucene_Index_TermInfo(count($this->_termDocs[$termId]),
                                            $freqPointer, $proxPointer, $skipOffset);

            $this->_dumpTermDictEntry($tisFile, $prevTerm, $term, $prevTermInfo, $termInfo);

            if ($termCount % self::$indexInterval == 0) {
                $this->_dumpTermDictEntry($tiiFile, $prevIndexTerm, $term, $prevIndexTermInfo, $termInfo);

                $indexPosition = $tisFile->tell();
                $tiiFile->writeVInt($indexPosition - $prevIndexPosition);
                $prevIndexPosition = $indexPosition;
            }
            $termCount++;
        }

        $this->_files[] = $this->_name . '.tis';
        $this->_files[] = $this->_name . '.tii';
        $this->_files[] = $this->_name . '.frq';
        $this->_files[] = $this->_name . '.prx';
    }


    /**
     * Generate compound index file
     */
    private function _generateCFS()
    {
        $cfsFile = $this->_directory->createFile($this->_name . '.cfs');
        $cfsFile->writeVInt(count($this->_files));

        $dataOffsetPointers = array();
        foreach ($this->_files as $fileName) {
            $dataOffsetPointers[$fileName] = $cfsFile->tell();
            $cfsFile->writeLong(0); // write dummy data
            $cfsFile->writeString($fileName);
        }

        foreach ($this->_files as $fileName) {
            // Get actual data offset
            $dataOffset = $cfsFile->tell();
            // Seek to the data offset pointer
            $cfsFile->seek($dataOffsetPointers[$fileName]);
            // Write actual data offset value
            $cfsFile->writeLong($dataOffset);
            // Seek back to the end of file
            $cfsFile->seek($dataOffset);

            $dataFile = $this->_directory->getFileObject($fileName);
            $cfsFile->writeBytes($dataFile->readBytes($this->_directory->fileLength($fileName)));

            $this->_directory->deleteFile($fileName);
        }
    }


    /**
     * Close segment, write it to disk and return segment info
     *
     * @return Zend_Search_Lucene_Index_SegmentInfo
     */
    public function close()
    {
        if ($this->_docCount == 0) {
            return null;
        }

        $this->_dumpFNM();
        $this->_dumpDictionary();

        $this->_generateCFS();

        return new Zend_Search_Lucene_Index_SegmentInfo($this->_name,
                                                        $this->_docCount,
                                                        $this->_directory);
    }

}