SegmentWriter.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Search_Lucene
  17. * @subpackage Index
  18. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /** Zend_Search_Lucene_Index_SegmentInfo */
  23. require_once 'Zend/Search/Lucene/Index/SegmentInfo.php';
  24. /**
  25. * @category Zend
  26. * @package Zend_Search_Lucene
  27. * @subpackage Index
  28. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  29. * @license http://framework.zend.com/license/new-bsd New BSD License
  30. */
  31. abstract class Zend_Search_Lucene_Index_SegmentWriter
  32. {
  33. /**
  34. * Expert: The fraction of terms in the "dictionary" which should be stored
  35. * in RAM. Smaller values use more memory, but make searching slightly
  36. * faster, while larger values use less memory and make searching slightly
  37. * slower. Searching is typically not dominated by dictionary lookup, so
  38. * tweaking this is rarely useful.
  39. *
  40. * @var integer
  41. */
  42. public static $indexInterval = 128;
  43. /**
  44. * Expert: The fraction of TermDocs entries stored in skip tables.
  45. * Larger values result in smaller indexes, greater acceleration, but fewer
  46. * accelerable cases, while smaller values result in bigger indexes,
  47. * less acceleration and more
  48. * accelerable cases. More detailed experiments would be useful here.
  49. *
  50. * 0x7FFFFFFF indicates that we don't use skip data
  51. *
  52. * Note: not used in current implementation
  53. *
  54. * @var integer
  55. */
  56. public static $skipInterval = 0x7FFFFFFF;
  57. /**
  58. * Expert: The maximum number of skip levels. Smaller values result in
  59. * slightly smaller indexes, but slower skipping in big posting lists.
  60. *
  61. * 0 indicates that we don't use skip data
  62. *
  63. * Note: not used in current implementation
  64. *
  65. * @var integer
  66. */
  67. public static $maxSkipLevels = 0;
  68. /**
  69. * Number of docs in a segment
  70. *
  71. * @var integer
  72. */
  73. protected $_docCount = 0;
  74. /**
  75. * Segment name
  76. *
  77. * @var string
  78. */
  79. protected $_name;
  80. /**
  81. * File system adapter.
  82. *
  83. * @var Zend_Search_Lucene_Storage_Directory
  84. */
  85. protected $_directory;
  86. /**
  87. * List of the index files.
  88. * Used for automatic compound file generation
  89. *
  90. * @var unknown_type
  91. */
  92. protected $_files = array();
  93. /**
  94. * Segment fields. Array of Zend_Search_Lucene_Index_FieldInfo objects for this segment
  95. *
  96. * @var array
  97. */
  98. protected $_fields = array();
  99. /**
  100. * Normalization factors.
  101. * An array fieldName => normVector
  102. * normVector is a binary string.
  103. * Each byte corresponds to an indexed document in a segment and
  104. * encodes normalization factor (float value, encoded by
  105. * Zend_Search_Lucene_Search_Similarity::encodeNorm())
  106. *
  107. * @var array
  108. */
  109. protected $_norms = array();
  110. /**
  111. * '.fdx' file - Stored Fields, the field index.
  112. *
  113. * @var Zend_Search_Lucene_Storage_File
  114. */
  115. protected $_fdxFile = null;
  116. /**
  117. * '.fdt' file - Stored Fields, the field data.
  118. *
  119. * @var Zend_Search_Lucene_Storage_File
  120. */
  121. protected $_fdtFile = null;
  122. /**
  123. * Object constructor.
  124. *
  125. * @param Zend_Search_Lucene_Storage_Directory $directory
  126. * @param string $name
  127. */
  128. public function __construct(Zend_Search_Lucene_Storage_Directory $directory, $name)
  129. {
  130. $this->_directory = $directory;
  131. $this->_name = $name;
  132. }
  133. /**
  134. * Add field to the segment
  135. *
  136. * Returns actual field number
  137. *
  138. * @param Zend_Search_Lucene_Field $field
  139. * @return integer
  140. */
  141. public function addField(Zend_Search_Lucene_Field $field)
  142. {
  143. if (!isset($this->_fields[$field->name])) {
  144. $fieldNumber = count($this->_fields);
  145. $this->_fields[$field->name] =
  146. new Zend_Search_Lucene_Index_FieldInfo($field->name,
  147. $field->isIndexed,
  148. $fieldNumber,
  149. $field->storeTermVector);
  150. return $fieldNumber;
  151. } else {
  152. $this->_fields[$field->name]->isIndexed |= $field->isIndexed;
  153. $this->_fields[$field->name]->storeTermVector |= $field->storeTermVector;
  154. return $this->_fields[$field->name]->number;
  155. }
  156. }
  157. /**
  158. * Add fieldInfo to the segment
  159. *
  160. * Returns actual field number
  161. *
  162. * @param Zend_Search_Lucene_Index_FieldInfo $fieldInfo
  163. * @return integer
  164. */
  165. public function addFieldInfo(Zend_Search_Lucene_Index_FieldInfo $fieldInfo)
  166. {
  167. if (!isset($this->_fields[$fieldInfo->name])) {
  168. $fieldNumber = count($this->_fields);
  169. $this->_fields[$fieldInfo->name] =
  170. new Zend_Search_Lucene_Index_FieldInfo($fieldInfo->name,
  171. $fieldInfo->isIndexed,
  172. $fieldNumber,
  173. $fieldInfo->storeTermVector);
  174. return $fieldNumber;
  175. } else {
  176. $this->_fields[$fieldInfo->name]->isIndexed |= $fieldInfo->isIndexed;
  177. $this->_fields[$fieldInfo->name]->storeTermVector |= $fieldInfo->storeTermVector;
  178. return $this->_fields[$fieldInfo->name]->number;
  179. }
  180. }
  181. /**
  182. * Returns array of FieldInfo objects.
  183. *
  184. * @return array
  185. */
  186. public function getFieldInfos()
  187. {
  188. return $this->_fields;
  189. }
  190. /**
  191. * Add stored fields information
  192. *
  193. * @param array $storedFields array of Zend_Search_Lucene_Field objects
  194. */
  195. public function addStoredFields($storedFields)
  196. {
  197. if (!isset($this->_fdxFile)) {
  198. $this->_fdxFile = $this->_directory->createFile($this->_name . '.fdx');
  199. $this->_fdtFile = $this->_directory->createFile($this->_name . '.fdt');
  200. $this->_files[] = $this->_name . '.fdx';
  201. $this->_files[] = $this->_name . '.fdt';
  202. }
  203. $this->_fdxFile->writeLong($this->_fdtFile->tell());
  204. $this->_fdtFile->writeVInt(count($storedFields));
  205. foreach ($storedFields as $field) {
  206. $this->_fdtFile->writeVInt($this->_fields[$field->name]->number);
  207. $fieldBits = ($field->isTokenized ? 0x01 : 0x00) |
  208. ($field->isBinary ? 0x02 : 0x00) |
  209. 0x00; /* 0x04 - third bit, compressed (ZLIB) */
  210. $this->_fdtFile->writeByte($fieldBits);
  211. if ($field->isBinary) {
  212. $this->_fdtFile->writeVInt(strlen($field->value));
  213. $this->_fdtFile->writeBytes($field->value);
  214. } else {
  215. $this->_fdtFile->writeString($field->getUtf8Value());
  216. }
  217. }
  218. $this->_docCount++;
  219. }
  220. /**
  221. * Returns the total number of documents in this segment.
  222. *
  223. * @return integer
  224. */
  225. public function count()
  226. {
  227. return $this->_docCount;
  228. }
  229. /**
  230. * Return segment name
  231. *
  232. * @return string
  233. */
  234. public function getName()
  235. {
  236. return $this->_name;
  237. }
  238. /**
  239. * Dump Field Info (.fnm) segment file
  240. */
  241. protected function _dumpFNM()
  242. {
  243. $fnmFile = $this->_directory->createFile($this->_name . '.fnm');
  244. $fnmFile->writeVInt(count($this->_fields));
  245. $nrmFile = $this->_directory->createFile($this->_name . '.nrm');
  246. // Write header
  247. $nrmFile->writeBytes('NRM');
  248. // Write format specifier
  249. $nrmFile->writeByte((int)0xFF);
  250. foreach ($this->_fields as $field) {
  251. $fnmFile->writeString($field->name);
  252. $fnmFile->writeByte(($field->isIndexed ? 0x01 : 0x00) |
  253. ($field->storeTermVector ? 0x02 : 0x00)
  254. // not supported yet 0x04 /* term positions are stored with the term vectors */ |
  255. // not supported yet 0x08 /* term offsets are stored with the term vectors */ |
  256. );
  257. if ($field->isIndexed) {
  258. // pre-2.1 index mode (not used now)
  259. // $normFileName = $this->_name . '.f' . $field->number;
  260. // $fFile = $this->_directory->createFile($normFileName);
  261. // $fFile->writeBytes($this->_norms[$field->name]);
  262. // $this->_files[] = $normFileName;
  263. $nrmFile->writeBytes($this->_norms[$field->name]);
  264. }
  265. }
  266. $this->_files[] = $this->_name . '.fnm';
  267. $this->_files[] = $this->_name . '.nrm';
  268. }
  269. /**
  270. * Term Dictionary file
  271. *
  272. * @var Zend_Search_Lucene_Storage_File
  273. */
  274. private $_tisFile = null;
  275. /**
  276. * Term Dictionary index file
  277. *
  278. * @var Zend_Search_Lucene_Storage_File
  279. */
  280. private $_tiiFile = null;
  281. /**
  282. * Frequencies file
  283. *
  284. * @var Zend_Search_Lucene_Storage_File
  285. */
  286. private $_frqFile = null;
  287. /**
  288. * Positions file
  289. *
  290. * @var Zend_Search_Lucene_Storage_File
  291. */
  292. private $_prxFile = null;
  293. /**
  294. * Number of written terms
  295. *
  296. * @var integer
  297. */
  298. private $_termCount;
  299. /**
  300. * Last saved term
  301. *
  302. * @var Zend_Search_Lucene_Index_Term
  303. */
  304. private $_prevTerm;
  305. /**
  306. * Last saved term info
  307. *
  308. * @var Zend_Search_Lucene_Index_TermInfo
  309. */
  310. private $_prevTermInfo;
  311. /**
  312. * Last saved index term
  313. *
  314. * @var Zend_Search_Lucene_Index_Term
  315. */
  316. private $_prevIndexTerm;
  317. /**
  318. * Last saved index term info
  319. *
  320. * @var Zend_Search_Lucene_Index_TermInfo
  321. */
  322. private $_prevIndexTermInfo;
  323. /**
  324. * Last term dictionary file position
  325. *
  326. * @var integer
  327. */
  328. private $_lastIndexPosition;
  329. /**
  330. * Create dicrionary, frequency and positions files and write necessary headers
  331. */
  332. public function initializeDictionaryFiles()
  333. {
  334. $this->_tisFile = $this->_directory->createFile($this->_name . '.tis');
  335. $this->_tisFile->writeInt((int)0xFFFFFFFD);
  336. $this->_tisFile->writeLong(0 /* dummy data for terms count */);
  337. $this->_tisFile->writeInt(self::$indexInterval);
  338. $this->_tisFile->writeInt(self::$skipInterval);
  339. $this->_tisFile->writeInt(self::$maxSkipLevels);
  340. $this->_tiiFile = $this->_directory->createFile($this->_name . '.tii');
  341. $this->_tiiFile->writeInt((int)0xFFFFFFFD);
  342. $this->_tiiFile->writeLong(0 /* dummy data for terms count */);
  343. $this->_tiiFile->writeInt(self::$indexInterval);
  344. $this->_tiiFile->writeInt(self::$skipInterval);
  345. $this->_tiiFile->writeInt(self::$maxSkipLevels);
  346. /** Dump dictionary header */
  347. $this->_tiiFile->writeVInt(0); // preffix length
  348. $this->_tiiFile->writeString(''); // suffix
  349. $this->_tiiFile->writeInt((int)0xFFFFFFFF); // field number
  350. $this->_tiiFile->writeByte((int)0x0F);
  351. $this->_tiiFile->writeVInt(0); // DocFreq
  352. $this->_tiiFile->writeVInt(0); // FreqDelta
  353. $this->_tiiFile->writeVInt(0); // ProxDelta
  354. $this->_tiiFile->writeVInt(24); // IndexDelta
  355. $this->_frqFile = $this->_directory->createFile($this->_name . '.frq');
  356. $this->_prxFile = $this->_directory->createFile($this->_name . '.prx');
  357. $this->_files[] = $this->_name . '.tis';
  358. $this->_files[] = $this->_name . '.tii';
  359. $this->_files[] = $this->_name . '.frq';
  360. $this->_files[] = $this->_name . '.prx';
  361. $this->_prevTerm = null;
  362. $this->_prevTermInfo = null;
  363. $this->_prevIndexTerm = null;
  364. $this->_prevIndexTermInfo = null;
  365. $this->_lastIndexPosition = 24;
  366. $this->_termCount = 0;
  367. }
  368. /**
  369. * Add term
  370. *
  371. * Term positions is an array( docId => array(pos1, pos2, pos3, ...), ... )
  372. *
  373. * @param Zend_Search_Lucene_Index_Term $termEntry
  374. * @param array $termDocs
  375. */
  376. public function addTerm($termEntry, $termDocs)
  377. {
  378. $freqPointer = $this->_frqFile->tell();
  379. $proxPointer = $this->_prxFile->tell();
  380. $prevDoc = 0;
  381. foreach ($termDocs as $docId => $termPositions) {
  382. $docDelta = ($docId - $prevDoc)*2;
  383. $prevDoc = $docId;
  384. if (count($termPositions) > 1) {
  385. $this->_frqFile->writeVInt($docDelta);
  386. $this->_frqFile->writeVInt(count($termPositions));
  387. } else {
  388. $this->_frqFile->writeVInt($docDelta + 1);
  389. }
  390. $prevPosition = 0;
  391. foreach ($termPositions as $position) {
  392. $this->_prxFile->writeVInt($position - $prevPosition);
  393. $prevPosition = $position;
  394. }
  395. }
  396. if (count($termDocs) >= self::$skipInterval) {
  397. /**
  398. * @todo Write Skip Data to a freq file.
  399. * It's not used now, but make index more optimal
  400. */
  401. $skipOffset = $this->_frqFile->tell() - $freqPointer;
  402. } else {
  403. $skipOffset = 0;
  404. }
  405. $term = new Zend_Search_Lucene_Index_Term($termEntry->text,
  406. $this->_fields[$termEntry->field]->number);
  407. $termInfo = new Zend_Search_Lucene_Index_TermInfo(count($termDocs),
  408. $freqPointer, $proxPointer, $skipOffset);
  409. $this->_dumpTermDictEntry($this->_tisFile, $this->_prevTerm, $term, $this->_prevTermInfo, $termInfo);
  410. if (($this->_termCount + 1) % self::$indexInterval == 0) {
  411. $this->_dumpTermDictEntry($this->_tiiFile, $this->_prevIndexTerm, $term, $this->_prevIndexTermInfo, $termInfo);
  412. $indexPosition = $this->_tisFile->tell();
  413. $this->_tiiFile->writeVInt($indexPosition - $this->_lastIndexPosition);
  414. $this->_lastIndexPosition = $indexPosition;
  415. }
  416. $this->_termCount++;
  417. }
  418. /**
  419. * Close dictionary
  420. */
  421. public function closeDictionaryFiles()
  422. {
  423. $this->_tisFile->seek(4);
  424. $this->_tisFile->writeLong($this->_termCount);
  425. $this->_tiiFile->seek(4);
  426. // + 1 is used to count an additional special index entry (empty term at the start of the list)
  427. $this->_tiiFile->writeLong(($this->_termCount - $this->_termCount % self::$indexInterval)/self::$indexInterval + 1);
  428. }
  429. /**
  430. * Dump Term Dictionary segment file entry.
  431. * Used to write entry to .tis or .tii files
  432. *
  433. * @param Zend_Search_Lucene_Storage_File $dicFile
  434. * @param Zend_Search_Lucene_Index_Term $prevTerm
  435. * @param Zend_Search_Lucene_Index_Term $term
  436. * @param Zend_Search_Lucene_Index_TermInfo $prevTermInfo
  437. * @param Zend_Search_Lucene_Index_TermInfo $termInfo
  438. */
  439. protected function _dumpTermDictEntry(Zend_Search_Lucene_Storage_File $dicFile,
  440. &$prevTerm, Zend_Search_Lucene_Index_Term $term,
  441. &$prevTermInfo, Zend_Search_Lucene_Index_TermInfo $termInfo)
  442. {
  443. if (isset($prevTerm) && $prevTerm->field == $term->field) {
  444. $matchedBytes = 0;
  445. $maxBytes = min(strlen($prevTerm->text), strlen($term->text));
  446. while ($matchedBytes < $maxBytes &&
  447. $prevTerm->text[$matchedBytes] == $term->text[$matchedBytes]) {
  448. $matchedBytes++;
  449. }
  450. // Calculate actual matched UTF-8 pattern
  451. $prefixBytes = 0;
  452. $prefixChars = 0;
  453. while ($prefixBytes < $matchedBytes) {
  454. $charBytes = 1;
  455. if ((ord($term->text[$prefixBytes]) & 0xC0) == 0xC0) {
  456. $charBytes++;
  457. if (ord($term->text[$prefixBytes]) & 0x20 ) {
  458. $charBytes++;
  459. if (ord($term->text[$prefixBytes]) & 0x10 ) {
  460. $charBytes++;
  461. }
  462. }
  463. }
  464. if ($prefixBytes + $charBytes > $matchedBytes) {
  465. // char crosses matched bytes boundary
  466. // skip char
  467. break;
  468. }
  469. $prefixChars++;
  470. $prefixBytes += $charBytes;
  471. }
  472. // Write preffix length
  473. $dicFile->writeVInt($prefixChars);
  474. // Write suffix
  475. $dicFile->writeString(substr($term->text, $prefixBytes));
  476. } else {
  477. // Write preffix length
  478. $dicFile->writeVInt(0);
  479. // Write suffix
  480. $dicFile->writeString($term->text);
  481. }
  482. // Write field number
  483. $dicFile->writeVInt($term->field);
  484. // DocFreq (the count of documents which contain the term)
  485. $dicFile->writeVInt($termInfo->docFreq);
  486. $prevTerm = $term;
  487. if (!isset($prevTermInfo)) {
  488. // Write FreqDelta
  489. $dicFile->writeVInt($termInfo->freqPointer);
  490. // Write ProxDelta
  491. $dicFile->writeVInt($termInfo->proxPointer);
  492. } else {
  493. // Write FreqDelta
  494. $dicFile->writeVInt($termInfo->freqPointer - $prevTermInfo->freqPointer);
  495. // Write ProxDelta
  496. $dicFile->writeVInt($termInfo->proxPointer - $prevTermInfo->proxPointer);
  497. }
  498. // Write SkipOffset - it's not 0 when $termInfo->docFreq > self::$skipInterval
  499. if ($termInfo->skipOffset != 0) {
  500. $dicFile->writeVInt($termInfo->skipOffset);
  501. }
  502. $prevTermInfo = $termInfo;
  503. }
  504. /**
  505. * Generate compound index file
  506. */
  507. protected function _generateCFS()
  508. {
  509. $cfsFile = $this->_directory->createFile($this->_name . '.cfs');
  510. $cfsFile->writeVInt(count($this->_files));
  511. $dataOffsetPointers = array();
  512. foreach ($this->_files as $fileName) {
  513. $dataOffsetPointers[$fileName] = $cfsFile->tell();
  514. $cfsFile->writeLong(0); // write dummy data
  515. $cfsFile->writeString($fileName);
  516. }
  517. foreach ($this->_files as $fileName) {
  518. // Get actual data offset
  519. $dataOffset = $cfsFile->tell();
  520. // Seek to the data offset pointer
  521. $cfsFile->seek($dataOffsetPointers[$fileName]);
  522. // Write actual data offset value
  523. $cfsFile->writeLong($dataOffset);
  524. // Seek back to the end of file
  525. $cfsFile->seek($dataOffset);
  526. $dataFile = $this->_directory->getFileObject($fileName);
  527. $byteCount = $this->_directory->fileLength($fileName);
  528. while ($byteCount > 0) {
  529. $data = $dataFile->readBytes(min($byteCount, 131072 /*128Kb*/));
  530. $byteCount -= strlen($data);
  531. $cfsFile->writeBytes($data);
  532. }
  533. $this->_directory->deleteFile($fileName);
  534. }
  535. }
  536. /**
  537. * Close segment, write it to disk and return segment info
  538. *
  539. * @return Zend_Search_Lucene_Index_SegmentInfo
  540. */
  541. abstract public function close();
  542. }