Subversion-Projekte lars-tiefland.prado

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/**
3
 * Zend Framework
4
 *
5
 * LICENSE
6
 *
7
 * This source file is subject to version 1.0 of the Zend Framework
8
 * license, that is bundled with this package in the file LICENSE, and
9
 * is available through the world-wide-web at the following URL:
10
 * http://www.zend.com/license/framework/1_0.txt. If you did not receive
11
 * a copy of the Zend Framework license and are unable to obtain it
12
 * through the world-wide-web, please send a note to license@zend.com
13
 * so we can mail you a copy immediately.
14
 *
15
 * @package    Zend_Search_Lucene
16
 * @subpackage Index
17
 * @copyright  Copyright (c) 2005-2006 Zend Technologies USA Inc. (http://www.zend.com)
18
 * @license    http://www.zend.com/license/framework/1_0.txt Zend Framework License version 1.0
19
 */
20
 
21
 
22
/** Zend_Search_Lucene_Exception */
23
require_once 'Zend/Search/Lucene/Exception.php';
24
 
25
/** Zend_Search_Lucene_Analysis_Analyzer */
26
require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';
27
 
28
/** Zend_Search_Lucene_Index_SegmentInfo */
29
require_once 'Zend/Search/Lucene/Index/SegmentInfo.php';
30
 
31
 
32
/**
33
 * @package    Zend_Search_Lucene
34
 * @subpackage Index
35
 * @copyright  Copyright (c) 2005-2006 Zend Technologies USA Inc. (http://www.zend.com)
36
 * @license    http://www.zend.com/license/framework/1_0.txt Zend Framework License version 1.0
37
 */
38
class Zend_Search_Lucene_Index_SegmentWriter
39
{
40
    /**
41
     * Expert: The fraction of terms in the "dictionary" which should be stored
42
     * in RAM.  Smaller values use more memory, but make searching slightly
43
     * faster, while larger values use less memory and make searching slightly
44
     * slower.  Searching is typically not dominated by dictionary lookup, so
45
     * tweaking this is rarely useful.
46
     *
47
     * @var integer
48
     */
49
    static public $indexInterval = 128;
50
 
51
    /** Expert: The fraction of TermDocs entries stored in skip tables.
52
     * Larger values result in smaller indexes, greater acceleration, but fewer
53
     * accelerable cases, while smaller values result in bigger indexes,
54
     * less acceleration and more
55
     * accelerable cases. More detailed experiments would be useful here.
56
     *
57
     * 0x0x7FFFFFFF indicates that we don't use skip data
58
     * Default value is 16
59
     *
60
     * @var integer
61
     */
62
    static public $skipInterval = 0x7FFFFFFF;
63
 
64
    /**
65
     * Number of docs in a segment
66
     *
67
     * @var integer
68
     */
69
    private $_docCount;
70
 
71
    /**
72
     * Segment name
73
     *
74
     * @var string
75
     */
76
    private $_name;
77
 
78
    /**
79
     * File system adapter.
80
     *
81
     * @var Zend_Search_Lucene_Storage_Directory
82
     */
83
    private $_directory;
84
 
85
    /**
86
     * List of the index files.
87
     * Used for automatic compound file generation
88
     *
89
     * @var unknown_type
90
     */
91
    private $_files;
92
 
93
    /**
94
     * Term Dictionary
95
     * Array of the Zend_Search_Lucene_Index_Term objects
96
     * Corresponding Zend_Search_Lucene_Index_TermInfo object stored in the $_termDictionaryInfos
97
     *
98
     * @var array
99
     */
100
    private $_termDictionary;
101
 
102
    /**
103
     * Documents, which contain the term
104
     *
105
     * @var array
106
     */
107
    private $_termDocs;
108
 
109
    /**
110
     * Segment fields. Array of Zend_Search_Lucene_Index_FieldInfo objects for this segment
111
     *
112
     * @var array
113
     */
114
    private $_fields;
115
 
116
    /**
117
     * Normalization factors.
118
     * An array fieldName => normVector
119
     * normVector is a binary string.
120
     * Each byte corresponds to an indexed document in a segment and
121
     * encodes normalization factor (float value, encoded by
122
     * Zend_Search_Lucene_Search_Similarity::encodeNorm())
123
     *
124
     * @var array
125
     */
126
    private $_norms;
127
 
128
 
129
    /**
130
     * '.fdx'  file - Stored Fields, the field index.
131
     *
132
     * @var Zend_Search_Lucene_Storage_File
133
     */
134
    private $_fdxFile;
135
 
136
    /**
137
     * '.fdx'  file - Stored Fields, the field data.
138
     *
139
     * @var Zend_Search_Lucene_Storage_File
140
     */
141
    private $_fdtFile;
142
 
143
 
144
    /**
145
     * Object constructor.
146
     *
147
     * @param Zend_Search_Lucene_Storage_Directory $directory
148
     * @param string $name
149
     */
150
    public function __construct($directory, $name)
151
    {
152
        $this->_directory = $directory;
153
        $this->_name      = $name;
154
        $this->_docCount  = 0;
155
 
156
        $this->_fields   = array();
157
        $this->_termDocs = array();
158
        $this->_files    = array();
159
        $this->_norms    = array();
160
 
161
        $this->_fdxFile = null;
162
        $this->_fdtFile = null;
163
    }
164
 
165
 
166
    /**
167
     * Add field to the segment
168
     *
169
     * @param Zend_Search_Lucene_Field $field
170
     */
171
    private function _addFieldInfo(Zend_Search_Lucene_Field $field)
172
    {
173
        if (!isset($this->_fields[$field->name])) {
174
            $this->_fields[$field->name] =
175
                                new Zend_Search_Lucene_Index_FieldInfo($field->name,
176
                                                                       $field->isIndexed,
177
                                                                       count($this->_fields),
178
                                                                       $field->storeTermVector);
179
        } else {
180
            $this->_fields[$field->name]->isIndexed       |= $field->isIndexed;
181
            $this->_fields[$field->name]->storeTermVector |= $field->storeTermVector;
182
        }
183
    }
184
 
185
 
186
    /**
187
     * Adds a document to this segment.
188
     *
189
     * @param Zend_Search_Lucene_Document $document
190
     * @throws Zend_Search_Lucene_Exception
191
     */
192
    public function addDocument(Zend_Search_Lucene_Document $document)
193
    {
194
        $storedFields = array();
195
 
196
        foreach ($document->getFieldNames() as $fieldName) {
197
            $field = $document->getField($fieldName);
198
            $this->_addFieldInfo($field);
199
 
200
            if ($field->storeTermVector) {
201
                /**
202
                 * @todo term vector storing support
203
                 */
204
                throw new Zend_Search_Lucene_Exception('Store term vector functionality is not supported yet.');
205
            }
206
 
207
            if ($field->isIndexed) {
208
                if ($field->isTokenized) {
209
                    $tokenList = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($field->stringValue);
210
                } else {
211
                    $tokenList = array();
212
                    $tokenList[] = new Zend_Search_Lucene_Analysis_Token($field->stringValue, 0, strlen($field->stringValue));
213
                }
214
 
215
                $position = 0;
216
                foreach ($tokenList as $token) {
217
                    $term = new Zend_Search_Lucene_Index_Term($token->getTermText(), $field->name);
218
                    $termKey = $term->key();
219
 
220
                    if (!isset($this->_termDictionary[$termKey])) {
221
                        // New term
222
                        $this->_termDictionary[$termKey] = $term;
223
                        $this->_termDocs[$termKey] = array();
224
                        $this->_termDocs[$termKey][$this->_docCount] = array();
225
                    } else if (!isset($this->_termDocs[$termKey][$this->_docCount])) {
226
                        // Existing term, but new term entry
227
                        $this->_termDocs[$termKey][$this->_docCount] = array();
228
                    }
229
                    $position += $token->getPositionIncrement();
230
                    $this->_termDocs[$termKey][$this->_docCount][] = $position;
231
                }
232
            }
233
 
234
            if ($field->isStored) {
235
                $storedFields[] = $field;
236
            }
237
        }
238
 
239
        if (count($storedFields) != 0) {
240
            if (!isset($this->_fdxFile)) {
241
                $this->_fdxFile = $this->_directory->createFile($this->_name . '.fdx');
242
                $this->_fdtFile = $this->_directory->createFile($this->_name . '.fdt');
243
 
244
                $this->_files[] = $this->_name . '.fdx';
245
                $this->_files[] = $this->_name . '.fdt';
246
            }
247
 
248
            $this->_fdxFile->writeLong($this->_fdtFile->tell());
249
 
250
            $this->_fdtFile->writeVInt(count($storedFields));
251
            foreach ($storedFields as $field) {
252
                $this->_fdtFile->writeVInt($this->_fields[$field->name]->number);
253
                $this->_fdtFile->writeByte($field->isTokenized ? 0x01 : 0x00 |
254
                                           $field->isBinary ?    0x02 : 0x00 |
255
                                           0x00 /* 0x04 - third bit, compressed (ZLIB) */ );
256
                if ($field->isBinary) {
257
                    $this->_fdtFile->writeVInt(strlen($field->stringValue));
258
                    $this->_fdtFile->writeBytes($field->stringValue);
259
                } else {
260
                    $this->_fdtFile->writeString($field->stringValue);
261
                }
262
            }
263
        }
264
 
265
        $this->_docCount++;
266
    }
267
 
268
 
269
    /**
270
     * Dump Field Info (.fnm) segment file
271
     */
272
    private function _dumpFNM()
273
    {
274
        $fnmFile = $this->_directory->createFile($this->_name . '.fnm');
275
        $fnmFile->writeVInt(count($this->_fields));
276
 
277
        foreach ($this->_fields as $field) {
278
            $fnmFile->writeString($field->name);
279
            $fnmFile->writeByte(($field->isIndexed       ? 0x01 : 0x00) |
280
                                ($field->storeTermVector ? 0x02 : 0x00) |
281
// not supported yet            0x04 /* term positions are stored with the term vectors */ |
282
// not supported yet            0x08 /* term offsets are stored with the term vectors */   |
283
/* not supported yet */         0x10 /* norms are omitted for the indexed field */
284
                               );
285
        }
286
 
287
        $this->_files[] = $this->_name . '.fnm';
288
    }
289
 
290
 
291
    /**
292
     * Dump Term Dictionary segment file entry.
293
     * Used to write entry to .tis or .tii files
294
     *
295
     * @param Zend_Search_Lucene_Storage_File $dicFile
296
     * @param Zend_Search_Lucene_Index_Term $prevTerm
297
     * @param Zend_Search_Lucene_Index_Term $term
298
     * @param Zend_Search_Lucene_Index_TermInfo $prevTermInfo
299
     * @param Zend_Search_Lucene_Index_TermInfo $termInfo
300
     */
301
    private function _dumpTermDictEntry(Zend_Search_Lucene_Storage_File $dicFile,
302
                                        &$prevTerm,     Zend_Search_Lucene_Index_Term     $term,
303
                                        &$prevTermInfo, Zend_Search_Lucene_Index_TermInfo $termInfo)
304
    {
305
        if (isset($prevTerm) && $prevTerm->field == $term->field) {
306
            $prefixLength = 0;
307
            while ($prefixLength < strlen($prevTerm->text) &&
308
                   $prefixLength < strlen($term->text) &&
309
                   $prevTerm->text{$prefixLength} == $term->text{$prefixLength}
310
                  ) {
311
                $prefixLength++;
312
            }
313
            // Write preffix length
314
            $dicFile->writeVInt($prefixLength);
315
            // Write suffix
316
            $dicFile->writeString( substr($term->text, $prefixLength) );
317
        } else {
318
            // Write preffix length
319
            $dicFile->writeVInt(0);
320
            // Write suffix
321
            $dicFile->writeString($term->text);
322
        }
323
        // Write field number
324
        $dicFile->writeVInt($term->field);
325
        // DocFreq (the count of documents which contain the term)
326
        $dicFile->writeVInt($termInfo->docFreq);
327
 
328
        $prevTerm = $term;
329
 
330
        if (!isset($prevTermInfo)) {
331
            // Write FreqDelta
332
            $dicFile->writeVInt($termInfo->freqPointer);
333
            // Write ProxDelta
334
            $dicFile->writeVInt($termInfo->proxPointer);
335
        } else {
336
            // Write FreqDelta
337
            $dicFile->writeVInt($termInfo->freqPointer - $prevTermInfo->freqPointer);
338
            // Write ProxDelta
339
            $dicFile->writeVInt($termInfo->proxPointer - $prevTermInfo->proxPointer);
340
        }
341
        // Write SkipOffset - it's not 0 when $termInfo->docFreq > self::$skipInterval
342
        if ($termInfo->skipOffset != 0) {
343
            $dicFile->writeVInt($termInfo->skipOffset);
344
        }
345
 
346
        $prevTermInfo = $termInfo;
347
    }
348
 
349
    /**
350
     * Dump Term Dictionary (.tis) and Term Dictionary Index (.tii) segment files
351
     */
352
    private function _dumpDictionary()
353
    {
354
        $tisFile = $this->_directory->createFile($this->_name . '.tis');
355
        $tisFile->writeInt((int)0xFFFFFFFE);
356
        $tisFile->writeLong(count($this->_termDictionary));
357
        $tisFile->writeInt(self::$indexInterval);
358
        $tisFile->writeInt(self::$skipInterval);
359
 
360
        $tiiFile = $this->_directory->createFile($this->_name . '.tii');
361
        $tiiFile->writeInt((int)0xFFFFFFFE);
362
        $tiiFile->writeLong((int)((count($this->_termDictionary) - 1)/self::$indexInterval) + 1);
363
        $tiiFile->writeInt(self::$indexInterval);
364
        $tiiFile->writeInt(self::$skipInterval);
365
 
366
        $frqFile = $this->_directory->createFile($this->_name . '.frq');
367
        $prxFile = $this->_directory->createFile($this->_name . '.prx');
368
 
369
        $termKeys = array_keys($this->_termDictionary);
370
        sort($termKeys, SORT_STRING);
371
 
372
        $termCount = 0;
373
 
374
        $prevTerm     = null;
375
        $prevTermInfo = null;
376
        $prevIndexTerm     = null;
377
        $prevIndexTermInfo = null;
378
        $prevIndexPosition = 0;
379
 
380
        foreach ($termKeys as $termId) {
381
            $freqPointer = $frqFile->tell();
382
            $proxPointer = $prxFile->tell();
383
 
384
            $prevDoc = 0;
385
            foreach ($this->_termDocs[$termId] as $docId => $termPositions) {
386
                $docDelta = ($docId - $prevDoc)*2;
387
                $prevDoc = $docId;
388
                if (count($termPositions) > 1) {
389
                    $frqFile->writeVInt($docDelta);
390
                    $frqFile->writeVInt(count($termPositions));
391
                } else {
392
                    $frqFile->writeVInt($docDelta + 1);
393
                }
394
 
395
                $prevPosition = 0;
396
                foreach ($termPositions as $position) {
397
                    $prxFile->writeVInt($position - $prevPosition);
398
                    $prevPosition = $position;
399
                }
400
            }
401
 
402
            if (count($this->_termDocs[$termId]) >= self::$skipInterval) {
403
                /**
404
                 * @todo Write Skip Data to a freq file.
405
                 * It's not used now, but must be implemented to be compatible with Lucene
406
                 */
407
                $skipOffset = $frqFile->tell() - $freqPointer;
408
            } else {
409
                $skipOffset = 0;
410
            }
411
 
412
            $term = new Zend_Search_Lucene_Index_Term($this->_termDictionary[$termId]->text,
413
                                                      $this->_fields[$this->_termDictionary[$termId]->field]->number);
414
            $termInfo = new Zend_Search_Lucene_Index_TermInfo(count($this->_termDocs[$termId]),
415
                                            $freqPointer, $proxPointer, $skipOffset);
416
 
417
            $this->_dumpTermDictEntry($tisFile, $prevTerm, $term, $prevTermInfo, $termInfo);
418
 
419
            if ($termCount % self::$indexInterval == 0) {
420
                $this->_dumpTermDictEntry($tiiFile, $prevIndexTerm, $term, $prevIndexTermInfo, $termInfo);
421
 
422
                $indexPosition = $tisFile->tell();
423
                $tiiFile->writeVInt($indexPosition - $prevIndexPosition);
424
                $prevIndexPosition = $indexPosition;
425
            }
426
            $termCount++;
427
        }
428
 
429
        $this->_files[] = $this->_name . '.tis';
430
        $this->_files[] = $this->_name . '.tii';
431
        $this->_files[] = $this->_name . '.frq';
432
        $this->_files[] = $this->_name . '.prx';
433
    }
434
 
435
 
436
    /**
437
     * Generate compound index file
438
     */
439
    private function _generateCFS()
440
    {
441
        $cfsFile = $this->_directory->createFile($this->_name . '.cfs');
442
        $cfsFile->writeVInt(count($this->_files));
443
 
444
        $dataOffsetPointers = array();
445
        foreach ($this->_files as $fileName) {
446
            $dataOffsetPointers[$fileName] = $cfsFile->tell();
447
            $cfsFile->writeLong(0); // write dummy data
448
            $cfsFile->writeString($fileName);
449
        }
450
 
451
        foreach ($this->_files as $fileName) {
452
            // Get actual data offset
453
            $dataOffset = $cfsFile->tell();
454
            // Seek to the data offset pointer
455
            $cfsFile->seek($dataOffsetPointers[$fileName]);
456
            // Write actual data offset value
457
            $cfsFile->writeLong($dataOffset);
458
            // Seek back to the end of file
459
            $cfsFile->seek($dataOffset);
460
 
461
            $dataFile = $this->_directory->getFileObject($fileName);
462
            $cfsFile->writeBytes($dataFile->readBytes($this->_directory->fileLength($fileName)));
463
 
464
            $this->_directory->deleteFile($fileName);
465
        }
466
    }
467
 
468
 
469
    /**
470
     * Close segment, write it to disk and return segment info
471
     *
472
     * @return Zend_Search_Lucene_Index_SegmentInfo
473
     */
474
    public function close()
475
    {
476
        if ($this->_docCount == 0) {
477
            return null;
478
        }
479
 
480
        $this->_dumpFNM();
481
        $this->_dumpDictionary();
482
 
483
        $this->_generateCFS();
484
 
485
        return new Zend_Search_Lucene_Index_SegmentInfo($this->_name,
486
                                                        $this->_docCount,
487
                                                        $this->_directory);
488
    }
489
 
490
}
491