SegmentInfo.php 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117
  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_DictionaryLoader */
  23. require_once 'Zend/Search/Lucene/Index/DictionaryLoader.php';
  24. /** Zend_Search_Lucene_Index_DocsFilter */
  25. require_once 'Zend/Search/Lucene/Index/DocsFilter.php';
  26. /** Zend_Search_Lucene_Index_TermsStream_Interface */
  27. require_once 'Zend/Search/Lucene/Index/TermsStream/Interface.php';
  28. /**
  29. * @category Zend
  30. * @package Zend_Search_Lucene
  31. * @subpackage Index
  32. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  33. * @license http://framework.zend.com/license/new-bsd New BSD License
  34. */
  35. class Zend_Search_Lucene_Index_SegmentInfo implements Zend_Search_Lucene_Index_TermsStream_Interface
  36. {
  37. /**
  38. * "Full scan vs fetch" boundary.
  39. *
  40. * If filter selectivity is less than this value, then full scan is performed
  41. * (since term entries fetching has some additional overhead).
  42. */
  43. const FULL_SCAN_VS_FETCH_BOUNDARY = 5;
  44. /**
  45. * Number of docs in a segment
  46. *
  47. * @var integer
  48. */
  49. private $_docCount;
  50. /**
  51. * Segment name
  52. *
  53. * @var string
  54. */
  55. private $_name;
  56. /**
  57. * Term Dictionary Index
  58. *
  59. * Array of arrays (Zend_Search_Lucene_Index_Term objects are represented as arrays because
  60. * of performance considerations)
  61. * [0] -> $termValue
  62. * [1] -> $termFieldNum
  63. *
  64. * Corresponding Zend_Search_Lucene_Index_TermInfo object stored in the $_termDictionaryInfos
  65. *
  66. * @var array
  67. */
  68. private $_termDictionary;
  69. /**
  70. * Term Dictionary Index TermInfos
  71. *
  72. * Array of arrays (Zend_Search_Lucene_Index_TermInfo objects are represented as arrays because
  73. * of performance considerations)
  74. * [0] -> $docFreq
  75. * [1] -> $freqPointer
  76. * [2] -> $proxPointer
  77. * [3] -> $skipOffset
  78. * [4] -> $indexPointer
  79. *
  80. * @var array
  81. */
  82. private $_termDictionaryInfos;
  83. /**
  84. * Segment fields. Array of Zend_Search_Lucene_Index_FieldInfo objects for this segment
  85. *
  86. * @var array
  87. */
  88. private $_fields;
  89. /**
  90. * Field positions in a dictionary.
  91. * (Term dictionary contains filelds ordered by names)
  92. *
  93. * @var array
  94. */
  95. private $_fieldsDicPositions;
  96. /**
  97. * Associative array where the key is the file name and the value is data offset
  98. * in a compound segment file (.csf).
  99. *
  100. * @var array
  101. */
  102. private $_segFiles;
  103. /**
  104. * Associative array where the key is the file name and the value is file size (.csf).
  105. *
  106. * @var array
  107. */
  108. private $_segFileSizes;
  109. /**
  110. * Delete file generation number
  111. *
  112. * -2 means autodetect latest delete generation
  113. * -1 means 'there is no delete file'
  114. * 0 means pre-2.1 format delete file
  115. * X specifies used delete file
  116. *
  117. * @var integer
  118. */
  119. private $_delGen;
  120. /**
  121. * Segment has single norms file
  122. *
  123. * If true then one .nrm file is used for all fields
  124. * Otherwise .fN files are used
  125. *
  126. * @var boolean
  127. */
  128. private $_hasSingleNormFile;
  129. /**
  130. * Use compound segment file (*.cfs) to collect all other segment files
  131. * (excluding .del files)
  132. *
  133. * @var boolean
  134. */
  135. private $_isCompound;
  136. /**
  137. * File system adapter.
  138. *
  139. * @var Zend_Search_Lucene_Storage_Directory_Filesystem
  140. */
  141. private $_directory;
  142. /**
  143. * Normalization factors.
  144. * An array fieldName => normVector
  145. * normVector is a binary string.
  146. * Each byte corresponds to an indexed document in a segment and
  147. * encodes normalization factor (float value, encoded by
  148. * Zend_Search_Lucene_Search_Similarity::encodeNorm())
  149. *
  150. * @var array
  151. */
  152. private $_norms = array();
  153. /**
  154. * List of deleted documents.
  155. * bitset if bitset extension is loaded or array otherwise.
  156. *
  157. * @var mixed
  158. */
  159. private $_deleted = null;
  160. /**
  161. * $this->_deleted update flag
  162. *
  163. * @var boolean
  164. */
  165. private $_deletedDirty = false;
  166. /**
  167. * True if segment uses shared doc store
  168. *
  169. * @var boolean
  170. */
  171. private $_usesSharedDocStore;
  172. /*
  173. * Shared doc store options.
  174. * It's an assotiative array with the following items:
  175. * - 'offset' => $docStoreOffset The starting document in the shared doc store files where this segment's documents begin
  176. * - 'segment' => $docStoreSegment The name of the segment that has the shared doc store files.
  177. * - 'isCompound' => $docStoreIsCompoundFile True, if compound file format is used for the shared doc store files (.cfx file).
  178. */
  179. private $_sharedDocStoreOptions;
  180. /**
  181. * Zend_Search_Lucene_Index_SegmentInfo constructor
  182. *
  183. * @param Zend_Search_Lucene_Storage_Directory $directory
  184. * @param string $name
  185. * @param integer $docCount
  186. * @param integer $delGen
  187. * @param array|null $docStoreOptions
  188. * @param boolean $hasSingleNormFile
  189. * @param boolean $isCompound
  190. */
  191. public function __construct(Zend_Search_Lucene_Storage_Directory $directory, $name, $docCount, $delGen = 0, $docStoreOptions = null, $hasSingleNormFile = false, $isCompound = null)
  192. {
  193. $this->_directory = $directory;
  194. $this->_name = $name;
  195. $this->_docCount = $docCount;
  196. if ($docStoreOptions !== null) {
  197. $this->_usesSharedDocStore = true;
  198. $this->_sharedDocStoreOptions = $docStoreOptions;
  199. if ($docStoreOptions['isCompound']) {
  200. $cfxFile = $this->_directory->getFileObject($docStoreOptions['segment'] . '.cfx');
  201. $cfxFilesCount = $cfxFile->readVInt();
  202. $cfxFiles = array();
  203. $cfxFileSizes = array();
  204. for ($count = 0; $count < $cfxFilesCount; $count++) {
  205. $dataOffset = $cfxFile->readLong();
  206. if ($count != 0) {
  207. $cfxFileSizes[$fileName] = $dataOffset - end($cfxFiles);
  208. }
  209. $fileName = $cfxFile->readString();
  210. $cfxFiles[$fileName] = $dataOffset;
  211. }
  212. if ($count != 0) {
  213. $cfxFileSizes[$fileName] = $this->_directory->fileLength($docStoreOptions['segment'] . '.cfx') - $dataOffset;
  214. }
  215. $this->_sharedDocStoreOptions['files'] = $cfxFiles;
  216. $this->_sharedDocStoreOptions['fileSizes'] = $cfxFileSizes;
  217. }
  218. }
  219. $this->_hasSingleNormFile = $hasSingleNormFile;
  220. $this->_delGen = $delGen;
  221. $this->_termDictionary = null;
  222. if ($isCompound !== null) {
  223. $this->_isCompound = $isCompound;
  224. } else {
  225. // It's a pre-2.1 segment or isCompound is set to 'unknown'
  226. // Detect if segment uses compound file
  227. require_once 'Zend/Search/Lucene/Exception.php';
  228. try {
  229. // Try to open compound file
  230. $this->_directory->getFileObject($name . '.cfs');
  231. // Compound file is found
  232. $this->_isCompound = true;
  233. } catch (Zend_Search_Lucene_Exception $e) {
  234. if (strpos($e->getMessage(), 'is not readable') !== false) {
  235. // Compound file is not found or is not readable
  236. $this->_isCompound = false;
  237. } else {
  238. throw $e;
  239. }
  240. }
  241. }
  242. $this->_segFiles = array();
  243. if ($this->_isCompound) {
  244. $cfsFile = $this->_directory->getFileObject($name . '.cfs');
  245. $segFilesCount = $cfsFile->readVInt();
  246. for ($count = 0; $count < $segFilesCount; $count++) {
  247. $dataOffset = $cfsFile->readLong();
  248. if ($count != 0) {
  249. $this->_segFileSizes[$fileName] = $dataOffset - end($this->_segFiles);
  250. }
  251. $fileName = $cfsFile->readString();
  252. $this->_segFiles[$fileName] = $dataOffset;
  253. }
  254. if ($count != 0) {
  255. $this->_segFileSizes[$fileName] = $this->_directory->fileLength($name . '.cfs') - $dataOffset;
  256. }
  257. }
  258. $fnmFile = $this->openCompoundFile('.fnm');
  259. $fieldsCount = $fnmFile->readVInt();
  260. $fieldNames = array();
  261. $fieldNums = array();
  262. $this->_fields = array();
  263. for ($count=0; $count < $fieldsCount; $count++) {
  264. $fieldName = $fnmFile->readString();
  265. $fieldBits = $fnmFile->readByte();
  266. $this->_fields[$count] = new Zend_Search_Lucene_Index_FieldInfo($fieldName,
  267. $fieldBits & 0x01 /* field is indexed */,
  268. $count,
  269. $fieldBits & 0x02 /* termvectors are stored */,
  270. $fieldBits & 0x10 /* norms are omitted */,
  271. $fieldBits & 0x20 /* payloads are stored */);
  272. if ($fieldBits & 0x10) {
  273. // norms are omitted for the indexed field
  274. $this->_norms[$count] = str_repeat(chr(Zend_Search_Lucene_Search_Similarity::encodeNorm(1.0)), $docCount);
  275. }
  276. $fieldNums[$count] = $count;
  277. $fieldNames[$count] = $fieldName;
  278. }
  279. array_multisort($fieldNames, SORT_ASC, SORT_REGULAR, $fieldNums);
  280. $this->_fieldsDicPositions = array_flip($fieldNums);
  281. if ($this->_delGen == -2) {
  282. // SegmentInfo constructor is invoked from index writer
  283. // Autodetect current delete file generation number
  284. $this->_delGen = $this->_detectLatestDelGen();
  285. }
  286. // Load deletions
  287. $this->_deleted = $this->_loadDelFile();
  288. }
  289. /**
  290. * Load detetions file
  291. *
  292. * Returns bitset or an array depending on bitset extension availability
  293. *
  294. * @return mixed
  295. * @throws Zend_Search_Lucene_Exception
  296. */
  297. private function _loadDelFile()
  298. {
  299. if ($this->_delGen == -1) {
  300. // There is no delete file for this segment
  301. return null;
  302. } else if ($this->_delGen == 0) {
  303. // It's a segment with pre-2.1 format delete file
  304. // Try to load deletions file
  305. return $this->_loadPre21DelFile();
  306. } else {
  307. // It's 2.1+ format deleteions file
  308. return $this->_load21DelFile();
  309. }
  310. }
  311. /**
  312. * Load pre-2.1 detetions file
  313. *
  314. * Returns bitset or an array depending on bitset extension availability
  315. *
  316. * @return mixed
  317. * @throws Zend_Search_Lucene_Exception
  318. */
  319. private function _loadPre21DelFile()
  320. {
  321. require_once 'Zend/Search/Lucene/Exception.php';
  322. try {
  323. // '.del' files always stored in a separate file
  324. // Segment compound is not used
  325. $delFile = $this->_directory->getFileObject($this->_name . '.del');
  326. $byteCount = $delFile->readInt();
  327. $byteCount = ceil($byteCount/8);
  328. $bitCount = $delFile->readInt();
  329. if ($bitCount == 0) {
  330. $delBytes = '';
  331. } else {
  332. $delBytes = $delFile->readBytes($byteCount);
  333. }
  334. if (extension_loaded('bitset')) {
  335. return $delBytes;
  336. } else {
  337. $deletions = array();
  338. for ($count = 0; $count < $byteCount; $count++) {
  339. $byte = ord($delBytes[$count]);
  340. for ($bit = 0; $bit < 8; $bit++) {
  341. if ($byte & (1<<$bit)) {
  342. $deletions[$count*8 + $bit] = 1;
  343. }
  344. }
  345. }
  346. return $deletions;
  347. }
  348. } catch(Zend_Search_Lucene_Exception $e) {
  349. if (strpos($e->getMessage(), 'is not readable') === false) {
  350. throw $e;
  351. }
  352. // There is no deletion file
  353. $this->_delGen = -1;
  354. return null;
  355. }
  356. }
  357. /**
  358. * Load 2.1+ format detetions file
  359. *
  360. * Returns bitset or an array depending on bitset extension availability
  361. *
  362. * @return mixed
  363. */
  364. private function _load21DelFile()
  365. {
  366. $delFile = $this->_directory->getFileObject($this->_name . '_' . base_convert($this->_delGen, 10, 36) . '.del');
  367. $format = $delFile->readInt();
  368. if ($format == (int)0xFFFFFFFF) {
  369. if (extension_loaded('bitset')) {
  370. $deletions = bitset_empty();
  371. } else {
  372. $deletions = array();
  373. }
  374. $byteCount = $delFile->readInt();
  375. $bitCount = $delFile->readInt();
  376. $delFileSize = $this->_directory->fileLength($this->_name . '_' . base_convert($this->_delGen, 10, 36) . '.del');
  377. $byteNum = 0;
  378. do {
  379. $dgap = $delFile->readVInt();
  380. $nonZeroByte = $delFile->readByte();
  381. $byteNum += $dgap;
  382. if (extension_loaded('bitset')) {
  383. for ($bit = 0; $bit < 8; $bit++) {
  384. if ($nonZeroByte & (1<<$bit)) {
  385. bitset_incl($deletions, $byteNum*8 + $bit);
  386. }
  387. }
  388. return $deletions;
  389. } else {
  390. for ($bit = 0; $bit < 8; $bit++) {
  391. if ($nonZeroByte & (1<<$bit)) {
  392. $deletions[$byteNum*8 + $bit] = 1;
  393. }
  394. }
  395. return (count($deletions) > 0) ? $deletions : null;
  396. }
  397. } while ($delFile->tell() < $delFileSize);
  398. } else {
  399. // $format is actually byte count
  400. $byteCount = ceil($format/8);
  401. $bitCount = $delFile->readInt();
  402. if ($bitCount == 0) {
  403. $delBytes = '';
  404. } else {
  405. $delBytes = $delFile->readBytes($byteCount);
  406. }
  407. if (extension_loaded('bitset')) {
  408. return $delBytes;
  409. } else {
  410. $deletions = array();
  411. for ($count = 0; $count < $byteCount; $count++) {
  412. $byte = ord($delBytes[$count]);
  413. for ($bit = 0; $bit < 8; $bit++) {
  414. if ($byte & (1<<$bit)) {
  415. $deletions[$count*8 + $bit] = 1;
  416. }
  417. }
  418. }
  419. return (count($deletions) > 0) ? $deletions : null;
  420. }
  421. }
  422. }
  423. /**
  424. * Opens index file stoted within compound index file
  425. *
  426. * @param string $extension
  427. * @param boolean $shareHandler
  428. * @throws Zend_Search_Lucene_Exception
  429. * @return Zend_Search_Lucene_Storage_File
  430. */
  431. public function openCompoundFile($extension, $shareHandler = true)
  432. {
  433. if (($extension == '.fdx' || $extension == '.fdt') && $this->_usesSharedDocStore) {
  434. $fdxFName = $this->_sharedDocStoreOptions['segment'] . '.fdx';
  435. $fdtFName = $this->_sharedDocStoreOptions['segment'] . '.fdt';
  436. if (!$this->_sharedDocStoreOptions['isCompound']) {
  437. $fdxFile = $this->_directory->getFileObject($fdxFName, $shareHandler);
  438. $fdxFile->seek($this->_sharedDocStoreOptions['offset']*8, SEEK_CUR);
  439. if ($extension == '.fdx') {
  440. // '.fdx' file is requested
  441. return $fdxFile;
  442. } else {
  443. // '.fdt' file is requested
  444. $fdtStartOffset = $fdxFile->readLong();
  445. $fdtFile = $this->_directory->getFileObject($fdtFName, $shareHandler);
  446. $fdtFile->seek($fdtStartOffset, SEEK_CUR);
  447. return $fdtFile;
  448. }
  449. }
  450. if( !isset($this->_sharedDocStoreOptions['files'][$fdxFName]) ) {
  451. require_once 'Zend/Search/Lucene/Exception.php';
  452. throw new Zend_Search_Lucene_Exception('Shared doc storage segment compound file doesn\'t contain '
  453. . $fdxFName . ' file.' );
  454. }
  455. if( !isset($this->_sharedDocStoreOptions['files'][$fdtFName]) ) {
  456. require_once 'Zend/Search/Lucene/Exception.php';
  457. throw new Zend_Search_Lucene_Exception('Shared doc storage segment compound file doesn\'t contain '
  458. . $fdtFName . ' file.' );
  459. }
  460. // Open shared docstore segment file
  461. $cfxFile = $this->_directory->getFileObject($this->_sharedDocStoreOptions['segment'] . '.cfx', $shareHandler);
  462. // Seek to the start of '.fdx' file within compound file
  463. $cfxFile->seek($this->_sharedDocStoreOptions['files'][$fdxFName]);
  464. // Seek to the start of current segment documents section
  465. $cfxFile->seek($this->_sharedDocStoreOptions['offset']*8, SEEK_CUR);
  466. if ($extension == '.fdx') {
  467. // '.fdx' file is requested
  468. return $cfxFile;
  469. } else {
  470. // '.fdt' file is requested
  471. $fdtStartOffset = $cfxFile->readLong();
  472. // Seek to the start of '.fdt' file within compound file
  473. $cfxFile->seek($this->_sharedDocStoreOptions['files'][$fdtFName]);
  474. // Seek to the start of current segment documents section
  475. $cfxFile->seek($fdtStartOffset, SEEK_CUR);
  476. return $fdtFile;
  477. }
  478. }
  479. $filename = $this->_name . $extension;
  480. if (!$this->_isCompound) {
  481. return $this->_directory->getFileObject($filename, $shareHandler);
  482. }
  483. if( !isset($this->_segFiles[$filename]) ) {
  484. require_once 'Zend/Search/Lucene/Exception.php';
  485. throw new Zend_Search_Lucene_Exception('Segment compound file doesn\'t contain '
  486. . $filename . ' file.' );
  487. }
  488. $file = $this->_directory->getFileObject($this->_name . '.cfs', $shareHandler);
  489. $file->seek($this->_segFiles[$filename]);
  490. return $file;
  491. }
  492. /**
  493. * Get compound file length
  494. *
  495. * @param string $extension
  496. * @return integer
  497. */
  498. public function compoundFileLength($extension)
  499. {
  500. if (($extension == '.fdx' || $extension == '.fdt') && $this->_usesSharedDocStore) {
  501. $filename = $this->_sharedDocStoreOptions['segment'] . $extension;
  502. if (!$this->_sharedDocStoreOptions['isCompound']) {
  503. return $this->_directory->fileLength($filename);
  504. }
  505. if( !isset($this->_sharedDocStoreOptions['fileSizes'][$filename]) ) {
  506. require_once 'Zend/Search/Lucene/Exception.php';
  507. throw new Zend_Search_Lucene_Exception('Shared doc store compound file doesn\'t contain '
  508. . $filename . ' file.' );
  509. }
  510. return $this->_sharedDocStoreOptions['fileSizes'][$filename];
  511. }
  512. $filename = $this->_name . $extension;
  513. // Try to get common file first
  514. if ($this->_directory->fileExists($filename)) {
  515. return $this->_directory->fileLength($filename);
  516. }
  517. if( !isset($this->_segFileSizes[$filename]) ) {
  518. require_once 'Zend/Search/Lucene/Exception.php';
  519. throw new Zend_Search_Lucene_Exception('Index compound file doesn\'t contain '
  520. . $filename . ' file.' );
  521. }
  522. return $this->_segFileSizes[$filename];
  523. }
  524. /**
  525. * Returns field index or -1 if field is not found
  526. *
  527. * @param string $fieldName
  528. * @return integer
  529. */
  530. public function getFieldNum($fieldName)
  531. {
  532. foreach( $this->_fields as $field ) {
  533. if( $field->name == $fieldName ) {
  534. return $field->number;
  535. }
  536. }
  537. return -1;
  538. }
  539. /**
  540. * Returns field info for specified field
  541. *
  542. * @param integer $fieldNum
  543. * @return Zend_Search_Lucene_Index_FieldInfo
  544. */
  545. public function getField($fieldNum)
  546. {
  547. return $this->_fields[$fieldNum];
  548. }
  549. /**
  550. * Returns array of fields.
  551. * if $indexed parameter is true, then returns only indexed fields.
  552. *
  553. * @param boolean $indexed
  554. * @return array
  555. */
  556. public function getFields($indexed = false)
  557. {
  558. $result = array();
  559. foreach( $this->_fields as $field ) {
  560. if( (!$indexed) || $field->isIndexed ) {
  561. $result[ $field->name ] = $field->name;
  562. }
  563. }
  564. return $result;
  565. }
  566. /**
  567. * Returns array of FieldInfo objects.
  568. *
  569. * @return array
  570. */
  571. public function getFieldInfos()
  572. {
  573. return $this->_fields;
  574. }
  575. /**
  576. * Returns actual deletions file generation number.
  577. *
  578. * @return integer
  579. */
  580. public function getDelGen()
  581. {
  582. return $this->_delGen;
  583. }
  584. /**
  585. * Returns the total number of documents in this segment (including deleted documents).
  586. *
  587. * @return integer
  588. */
  589. public function count()
  590. {
  591. return $this->_docCount;
  592. }
  593. /**
  594. * Returns number of deleted documents.
  595. *
  596. * @return integer
  597. */
  598. private function _deletedCount()
  599. {
  600. if ($this->_deleted === null) {
  601. return 0;
  602. }
  603. if (extension_loaded('bitset')) {
  604. return count(bitset_to_array($this->_deleted));
  605. } else {
  606. return count($this->_deleted);
  607. }
  608. }
  609. /**
  610. * Returns the total number of non-deleted documents in this segment.
  611. *
  612. * @return integer
  613. */
  614. public function numDocs()
  615. {
  616. if ($this->hasDeletions()) {
  617. return $this->_docCount - $this->_deletedCount();
  618. } else {
  619. return $this->_docCount;
  620. }
  621. }
  622. /**
  623. * Get field position in a fields dictionary
  624. *
  625. * @param integer $fieldNum
  626. * @return integer
  627. */
  628. private function _getFieldPosition($fieldNum) {
  629. // Treat values which are not in a translation table as a 'direct value'
  630. return isset($this->_fieldsDicPositions[$fieldNum]) ?
  631. $this->_fieldsDicPositions[$fieldNum] : $fieldNum;
  632. }
  633. /**
  634. * Return segment name
  635. *
  636. * @return string
  637. */
  638. public function getName()
  639. {
  640. return $this->_name;
  641. }
  642. /**
  643. * TermInfo cache
  644. *
  645. * Size is 1024.
  646. * Numbers are used instead of class constants because of performance considerations
  647. *
  648. * @var array
  649. */
  650. private $_termInfoCache = array();
  651. private function _cleanUpTermInfoCache()
  652. {
  653. // Clean 256 term infos
  654. foreach ($this->_termInfoCache as $key => $termInfo) {
  655. unset($this->_termInfoCache[$key]);
  656. // leave 768 last used term infos
  657. if (count($this->_termInfoCache) == 768) {
  658. break;
  659. }
  660. }
  661. }
  662. /**
  663. * Load terms dictionary index
  664. *
  665. * @throws Zend_Search_Lucene_Exception
  666. */
  667. private function _loadDictionaryIndex()
  668. {
  669. // Check, if index is already serialized
  670. if ($this->_directory->fileExists($this->_name . '.sti')) {
  671. // Load serialized dictionary index data
  672. $stiFile = $this->_directory->getFileObject($this->_name . '.sti');
  673. $stiFileData = $stiFile->readBytes($this->_directory->fileLength($this->_name . '.sti'));
  674. // Load dictionary index data
  675. if (($unserializedData = @unserialize($stiFileData)) !== false) {
  676. list($this->_termDictionary, $this->_termDictionaryInfos) = $unserializedData;
  677. return;
  678. }
  679. }
  680. // Load data from .tii file and generate .sti file
  681. // Prefetch dictionary index data
  682. $tiiFile = $this->openCompoundFile('.tii');
  683. $tiiFileData = $tiiFile->readBytes($this->compoundFileLength('.tii'));
  684. // Load dictionary index data
  685. list($this->_termDictionary, $this->_termDictionaryInfos) =
  686. Zend_Search_Lucene_Index_DictionaryLoader::load($tiiFileData);
  687. $stiFileData = serialize(array($this->_termDictionary, $this->_termDictionaryInfos));
  688. $stiFile = $this->_directory->createFile($this->_name . '.sti');
  689. $stiFile->writeBytes($stiFileData);
  690. }
  691. /**
  692. * Scans terms dictionary and returns term info
  693. *
  694. * @param Zend_Search_Lucene_Index_Term $term
  695. * @return Zend_Search_Lucene_Index_TermInfo
  696. */
  697. public function getTermInfo(Zend_Search_Lucene_Index_Term $term)
  698. {
  699. $termKey = $term->key();
  700. if (isset($this->_termInfoCache[$termKey])) {
  701. $termInfo = $this->_termInfoCache[$termKey];
  702. // Move termInfo to the end of cache
  703. unset($this->_termInfoCache[$termKey]);
  704. $this->_termInfoCache[$termKey] = $termInfo;
  705. return $termInfo;
  706. }
  707. if ($this->_termDictionary === null) {
  708. $this->_loadDictionaryIndex();
  709. }
  710. $searchField = $this->getFieldNum($term->field);
  711. if ($searchField == -1) {
  712. return null;
  713. }
  714. $searchDicField = $this->_getFieldPosition($searchField);
  715. // search for appropriate value in dictionary
  716. $lowIndex = 0;
  717. $highIndex = count($this->_termDictionary)-1;
  718. while ($highIndex >= $lowIndex) {
  719. // $mid = ($highIndex - $lowIndex)/2;
  720. $mid = ($highIndex + $lowIndex) >> 1;
  721. $midTerm = $this->_termDictionary[$mid];
  722. $fieldNum = $this->_getFieldPosition($midTerm[0] /* field */);
  723. $delta = $searchDicField - $fieldNum;
  724. if ($delta == 0) {
  725. $delta = strcmp($term->text, $midTerm[1] /* text */);
  726. }
  727. if ($delta < 0) {
  728. $highIndex = $mid-1;
  729. } elseif ($delta > 0) {
  730. $lowIndex = $mid+1;
  731. } else {
  732. // return $this->_termDictionaryInfos[$mid]; // We got it!
  733. $a = $this->_termDictionaryInfos[$mid];
  734. $termInfo = new Zend_Search_Lucene_Index_TermInfo($a[0], $a[1], $a[2], $a[3], $a[4]);
  735. // Put loaded termInfo into cache
  736. $this->_termInfoCache[$termKey] = $termInfo;
  737. return $termInfo;
  738. }
  739. }
  740. if ($highIndex == -1) {
  741. // Term is out of the dictionary range
  742. return null;
  743. }
  744. $prevPosition = $highIndex;
  745. $prevTerm = $this->_termDictionary[$prevPosition];
  746. $prevTermInfo = $this->_termDictionaryInfos[$prevPosition];
  747. $tisFile = $this->openCompoundFile('.tis');
  748. $tiVersion = $tisFile->readInt();
  749. if ($tiVersion != (int)0xFFFFFFFE /* pre-2.1 format */ &&
  750. $tiVersion != (int)0xFFFFFFFD /* 2.1+ format */) {
  751. require_once 'Zend/Search/Lucene/Exception.php';
  752. throw new Zend_Search_Lucene_Exception('Wrong TermInfoFile file format');
  753. }
  754. $termCount = $tisFile->readLong();
  755. $indexInterval = $tisFile->readInt();
  756. $skipInterval = $tisFile->readInt();
  757. if ($tiVersion == (int)0xFFFFFFFD /* 2.1+ format */) {
  758. $maxSkipLevels = $tisFile->readInt();
  759. }
  760. $tisFile->seek($prevTermInfo[4] /* indexPointer */ - (($tiVersion == (int)0xFFFFFFFD)? 24 : 20) /* header size*/, SEEK_CUR);
  761. $termValue = $prevTerm[1] /* text */;
  762. $termFieldNum = $prevTerm[0] /* field */;
  763. $freqPointer = $prevTermInfo[1] /* freqPointer */;
  764. $proxPointer = $prevTermInfo[2] /* proxPointer */;
  765. for ($count = $prevPosition*$indexInterval + 1;
  766. $count <= $termCount &&
  767. ( $this->_getFieldPosition($termFieldNum) < $searchDicField ||
  768. ($this->_getFieldPosition($termFieldNum) == $searchDicField &&
  769. strcmp($termValue, $term->text) < 0) );
  770. $count++) {
  771. $termPrefixLength = $tisFile->readVInt();
  772. $termSuffix = $tisFile->readString();
  773. $termFieldNum = $tisFile->readVInt();
  774. $termValue = Zend_Search_Lucene_Index_Term::getPrefix($termValue, $termPrefixLength) . $termSuffix;
  775. $docFreq = $tisFile->readVInt();
  776. $freqPointer += $tisFile->readVInt();
  777. $proxPointer += $tisFile->readVInt();
  778. if( $docFreq >= $skipInterval ) {
  779. $skipOffset = $tisFile->readVInt();
  780. } else {
  781. $skipOffset = 0;
  782. }
  783. }
  784. if ($termFieldNum == $searchField && $termValue == $term->text) {
  785. $termInfo = new Zend_Search_Lucene_Index_TermInfo($docFreq, $freqPointer, $proxPointer, $skipOffset);
  786. } else {
  787. $termInfo = null;
  788. }
  789. // Put loaded termInfo into cache
  790. $this->_termInfoCache[$termKey] = $termInfo;
  791. if (count($this->_termInfoCache) == 1024) {
  792. $this->_cleanUpTermInfoCache();
  793. }
  794. return $termInfo;
  795. }
  796. /**
  797. * Returns IDs of all the documents containing term.
  798. *
  799. * @param Zend_Search_Lucene_Index_Term $term
  800. * @param integer $shift
  801. * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
  802. * @return array
  803. */
  804. public function termDocs(Zend_Search_Lucene_Index_Term $term, $shift = 0, $docsFilter = null)
  805. {
  806. $termInfo = $this->getTermInfo($term);
  807. if (!$termInfo instanceof Zend_Search_Lucene_Index_TermInfo) {
  808. if ($docsFilter !== null && $docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
  809. $docsFilter->segmentFilters[$this->_name] = array();
  810. }
  811. return array();
  812. }
  813. $frqFile = $this->openCompoundFile('.frq');
  814. $frqFile->seek($termInfo->freqPointer,SEEK_CUR);
  815. $docId = 0;
  816. $result = array();
  817. if ($docsFilter !== null) {
  818. if (!$docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
  819. require_once 'Zend/Search/Lucene/Exception.php';
  820. throw new Zend_Search_Lucene_Exception('Documents filter must be an instance of Zend_Search_Lucene_Index_DocsFilter or null.');
  821. }
  822. if (isset($docsFilter->segmentFilters[$this->_name])) {
  823. // Filter already has some data for the current segment
  824. // Make short name for the filter (which doesn't need additional dereferencing)
  825. $filter = &$docsFilter->segmentFilters[$this->_name];
  826. // Check if filter is not empty
  827. if (count($filter) == 0) {
  828. return array();
  829. }
  830. if ($this->_docCount/count($filter) < self::FULL_SCAN_VS_FETCH_BOUNDARY) {
  831. // Perform fetching
  832. // ---------------------------------------------------------------
  833. $updatedFilterData = array();
  834. for( $count=0; $count < $termInfo->docFreq; $count++ ) {
  835. $docDelta = $frqFile->readVInt();
  836. if( $docDelta % 2 == 1 ) {
  837. $docId += ($docDelta-1)/2;
  838. } else {
  839. $docId += $docDelta/2;
  840. // read freq
  841. $frqFile->readVInt();
  842. }
  843. if (isset($filter[$docId])) {
  844. $result[] = $shift + $docId;
  845. $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  846. }
  847. }
  848. $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
  849. // ---------------------------------------------------------------
  850. } else {
  851. // Perform full scan
  852. $updatedFilterData = array();
  853. for( $count=0; $count < $termInfo->docFreq; $count++ ) {
  854. $docDelta = $frqFile->readVInt();
  855. if( $docDelta % 2 == 1 ) {
  856. $docId += ($docDelta-1)/2;
  857. } else {
  858. $docId += $docDelta/2;
  859. // read freq
  860. $frqFile->readVInt();
  861. }
  862. if (isset($filter[$docId])) {
  863. $result[] = $shift + $docId;
  864. $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  865. }
  866. }
  867. $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
  868. }
  869. } else {
  870. // Filter is present, but doesn't has data for the current segment yet
  871. $filterData = array();
  872. for( $count=0; $count < $termInfo->docFreq; $count++ ) {
  873. $docDelta = $frqFile->readVInt();
  874. if( $docDelta % 2 == 1 ) {
  875. $docId += ($docDelta-1)/2;
  876. } else {
  877. $docId += $docDelta/2;
  878. // read freq
  879. $frqFile->readVInt();
  880. }
  881. $result[] = $shift + $docId;
  882. $filterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  883. }
  884. $docsFilter->segmentFilters[$this->_name] = $filterData;
  885. }
  886. } else {
  887. for( $count=0; $count < $termInfo->docFreq; $count++ ) {
  888. $docDelta = $frqFile->readVInt();
  889. if( $docDelta % 2 == 1 ) {
  890. $docId += ($docDelta-1)/2;
  891. } else {
  892. $docId += $docDelta/2;
  893. // read freq
  894. $frqFile->readVInt();
  895. }
  896. $result[] = $shift + $docId;
  897. }
  898. }
  899. return $result;
  900. }
  901. /**
  902. * Returns term freqs array.
  903. * Result array structure: array(docId => freq, ...)
  904. *
  905. * @param Zend_Search_Lucene_Index_Term $term
  906. * @param integer $shift
  907. * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
  908. * @return Zend_Search_Lucene_Index_TermInfo
  909. */
  910. public function termFreqs(Zend_Search_Lucene_Index_Term $term, $shift = 0, $docsFilter = null)
  911. {
  912. $termInfo = $this->getTermInfo($term);
  913. if (!$termInfo instanceof Zend_Search_Lucene_Index_TermInfo) {
  914. if ($docsFilter !== null && $docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
  915. $docsFilter->segmentFilters[$this->_name] = array();
  916. }
  917. return array();
  918. }
  919. $frqFile = $this->openCompoundFile('.frq');
  920. $frqFile->seek($termInfo->freqPointer,SEEK_CUR);
  921. $result = array();
  922. $docId = 0;
  923. $result = array();
  924. if ($docsFilter !== null) {
  925. if (!$docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
  926. require_once 'Zend/Search/Lucene/Exception.php';
  927. throw new Zend_Search_Lucene_Exception('Documents filter must be an instance of Zend_Search_Lucene_Index_DocsFilter or null.');
  928. }
  929. if (isset($docsFilter->segmentFilters[$this->_name])) {
  930. // Filter already has some data for the current segment
  931. // Make short name for the filter (which doesn't need additional dereferencing)
  932. $filter = &$docsFilter->segmentFilters[$this->_name];
  933. // Check if filter is not empty
  934. if (count($filter) == 0) {
  935. return array();
  936. }
  937. if ($this->_docCount/count($filter) < self::FULL_SCAN_VS_FETCH_BOUNDARY) {
  938. // Perform fetching
  939. // ---------------------------------------------------------------
  940. $updatedFilterData = array();
  941. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  942. $docDelta = $frqFile->readVInt();
  943. if ($docDelta % 2 == 1) {
  944. $docId += ($docDelta-1)/2;
  945. if (isset($filter[$docId])) {
  946. $result[$shift + $docId] = 1;
  947. $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  948. }
  949. } else {
  950. $docId += $docDelta/2;
  951. if (isset($filter[$docId])) {
  952. $result[$shift + $docId] = $frqFile->readVInt();
  953. $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  954. }
  955. }
  956. }
  957. $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
  958. // ---------------------------------------------------------------
  959. } else {
  960. // Perform full scan
  961. $updatedFilterData = array();
  962. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  963. $docDelta = $frqFile->readVInt();
  964. if ($docDelta % 2 == 1) {
  965. $docId += ($docDelta-1)/2;
  966. if (isset($filter[$docId])) {
  967. $result[$shift + $docId] = 1;
  968. $updatedFilterData[$docId] = 1; // 1 is just some constant value, so we don't need additional var dereference here
  969. }
  970. } else {
  971. $docId += $docDelta/2;
  972. if (isset($filter[$docId])) {
  973. $result[$shift + $docId] = $frqFile->readVInt();
  974. $updatedFilterData[$docId] = 1; // 1 is just some constant value, so we don't need additional var dereference here
  975. }
  976. }
  977. }
  978. $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
  979. }
  980. } else {
  981. // Filter doesn't has data for current segment
  982. $filterData = array();
  983. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  984. $docDelta = $frqFile->readVInt();
  985. if ($docDelta % 2 == 1) {
  986. $docId += ($docDelta-1)/2;
  987. $result[$shift + $docId] = 1;
  988. $filterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  989. } else {
  990. $docId += $docDelta/2;
  991. $result[$shift + $docId] = $frqFile->readVInt();
  992. $filterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  993. }
  994. }
  995. $docsFilter->segmentFilters[$this->_name] = $filterData;
  996. }
  997. } else {
  998. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  999. $docDelta = $frqFile->readVInt();
  1000. if ($docDelta % 2 == 1) {
  1001. $docId += ($docDelta-1)/2;
  1002. $result[$shift + $docId] = 1;
  1003. } else {
  1004. $docId += $docDelta/2;
  1005. $result[$shift + $docId] = $frqFile->readVInt();
  1006. }
  1007. }
  1008. }
  1009. return $result;
  1010. }
  1011. /**
  1012. * Returns term positions array.
  1013. * Result array structure: array(docId => array(pos1, pos2, ...), ...)
  1014. *
  1015. * @param Zend_Search_Lucene_Index_Term $term
  1016. * @param integer $shift
  1017. * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
  1018. * @return Zend_Search_Lucene_Index_TermInfo
  1019. */
  1020. public function termPositions(Zend_Search_Lucene_Index_Term $term, $shift = 0, $docsFilter = null)
  1021. {
  1022. $termInfo = $this->getTermInfo($term);
  1023. if (!$termInfo instanceof Zend_Search_Lucene_Index_TermInfo) {
  1024. if ($docsFilter !== null && $docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
  1025. $docsFilter->segmentFilters[$this->_name] = array();
  1026. }
  1027. return array();
  1028. }
  1029. $frqFile = $this->openCompoundFile('.frq');
  1030. $frqFile->seek($termInfo->freqPointer,SEEK_CUR);
  1031. $docId = 0;
  1032. $freqs = array();
  1033. if ($docsFilter !== null) {
  1034. if (!$docsFilter instanceof Zend_Search_Lucene_Index_DocsFilter) {
  1035. require_once 'Zend/Search/Lucene/Exception.php';
  1036. throw new Zend_Search_Lucene_Exception('Documents filter must be an instance of Zend_Search_Lucene_Index_DocsFilter or null.');
  1037. }
  1038. if (isset($docsFilter->segmentFilters[$this->_name])) {
  1039. // Filter already has some data for the current segment
  1040. // Make short name for the filter (which doesn't need additional dereferencing)
  1041. $filter = &$docsFilter->segmentFilters[$this->_name];
  1042. // Check if filter is not empty
  1043. if (count($filter) == 0) {
  1044. return array();
  1045. }
  1046. if ($this->_docCount/count($filter) < self::FULL_SCAN_VS_FETCH_BOUNDARY) {
  1047. // Perform fetching
  1048. // ---------------------------------------------------------------
  1049. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  1050. $docDelta = $frqFile->readVInt();
  1051. if ($docDelta % 2 == 1) {
  1052. $docId += ($docDelta-1)/2;
  1053. $freqs[$docId] = 1;
  1054. } else {
  1055. $docId += $docDelta/2;
  1056. $freqs[$docId] = $frqFile->readVInt();
  1057. }
  1058. }
  1059. $updatedFilterData = array();
  1060. $result = array();
  1061. $prxFile = $this->openCompoundFile('.prx');
  1062. $prxFile->seek($termInfo->proxPointer, SEEK_CUR);
  1063. foreach ($freqs as $docId => $freq) {
  1064. $termPosition = 0;
  1065. $positions = array();
  1066. // we have to read .prx file to get right position for next doc
  1067. // even filter doesn't match current document
  1068. for ($count = 0; $count < $freq; $count++ ) {
  1069. $termPosition += $prxFile->readVInt();
  1070. $positions[] = $termPosition;
  1071. }
  1072. // Include into updated filter and into result only if doc is matched by filter
  1073. if (isset($filter[$docId])) {
  1074. $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  1075. $result[$shift + $docId] = $positions;
  1076. }
  1077. }
  1078. $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
  1079. // ---------------------------------------------------------------
  1080. } else {
  1081. // Perform full scan
  1082. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  1083. $docDelta = $frqFile->readVInt();
  1084. if ($docDelta % 2 == 1) {
  1085. $docId += ($docDelta-1)/2;
  1086. $freqs[$docId] = 1;
  1087. } else {
  1088. $docId += $docDelta/2;
  1089. $freqs[$docId] = $frqFile->readVInt();
  1090. }
  1091. }
  1092. $updatedFilterData = array();
  1093. $result = array();
  1094. $prxFile = $this->openCompoundFile('.prx');
  1095. $prxFile->seek($termInfo->proxPointer, SEEK_CUR);
  1096. foreach ($freqs as $docId => $freq) {
  1097. $termPosition = 0;
  1098. $positions = array();
  1099. // we have to read .prx file to get right position for next doc
  1100. // even filter doesn't match current document
  1101. for ($count = 0; $count < $freq; $count++ ) {
  1102. $termPosition += $prxFile->readVInt();
  1103. $positions[] = $termPosition;
  1104. }
  1105. // Include into updated filter and into result only if doc is matched by filter
  1106. if (isset($filter[$docId])) {
  1107. $updatedFilterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  1108. $result[$shift + $docId] = $positions;
  1109. }
  1110. }
  1111. $docsFilter->segmentFilters[$this->_name] = $updatedFilterData;
  1112. }
  1113. } else {
  1114. // Filter doesn't has data for current segment
  1115. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  1116. $docDelta = $frqFile->readVInt();
  1117. if ($docDelta % 2 == 1) {
  1118. $docId += ($docDelta-1)/2;
  1119. $freqs[$docId] = 1;
  1120. } else {
  1121. $docId += $docDelta/2;
  1122. $freqs[$docId] = $frqFile->readVInt();
  1123. }
  1124. }
  1125. $filterData = array();
  1126. $result = array();
  1127. $prxFile = $this->openCompoundFile('.prx');
  1128. $prxFile->seek($termInfo->proxPointer, SEEK_CUR);
  1129. foreach ($freqs as $docId => $freq) {
  1130. $filterData[$docId] = 1; // 1 is just a some constant value, so we don't need additional var dereference here
  1131. $termPosition = 0;
  1132. $positions = array();
  1133. for ($count = 0; $count < $freq; $count++ ) {
  1134. $termPosition += $prxFile->readVInt();
  1135. $positions[] = $termPosition;
  1136. }
  1137. $result[$shift + $docId] = $positions;
  1138. }
  1139. $docsFilter->segmentFilters[$this->_name] = $filterData;
  1140. }
  1141. } else {
  1142. for ($count = 0; $count < $termInfo->docFreq; $count++) {
  1143. $docDelta = $frqFile->readVInt();
  1144. if ($docDelta % 2 == 1) {
  1145. $docId += ($docDelta-1)/2;
  1146. $freqs[$docId] = 1;
  1147. } else {
  1148. $docId += $docDelta/2;
  1149. $freqs[$docId] = $frqFile->readVInt();
  1150. }
  1151. }
  1152. $result = array();
  1153. $prxFile = $this->openCompoundFile('.prx');
  1154. $prxFile->seek($termInfo->proxPointer, SEEK_CUR);
  1155. foreach ($freqs as $docId => $freq) {
  1156. $termPosition = 0;
  1157. $positions = array();
  1158. for ($count = 0; $count < $freq; $count++ ) {
  1159. $termPosition += $prxFile->readVInt();
  1160. $positions[] = $termPosition;
  1161. }
  1162. $result[$shift + $docId] = $positions;
  1163. }
  1164. }
  1165. return $result;
  1166. }
  1167. /**
  1168. * Load normalizatin factors from an index file
  1169. *
  1170. * @param integer $fieldNum
  1171. * @throws Zend_Search_Lucene_Exception
  1172. */
  1173. private function _loadNorm($fieldNum)
  1174. {
  1175. if ($this->_hasSingleNormFile) {
  1176. $normfFile = $this->openCompoundFile('.nrm');
  1177. $header = $normfFile->readBytes(3);
  1178. $headerFormatVersion = $normfFile->readByte();
  1179. if ($header != 'NRM' || $headerFormatVersion != (int)0xFF) {
  1180. require_once 'Zend/Search/Lucene/Exception.php';
  1181. throw new Zend_Search_Lucene_Exception('Wrong norms file format.');
  1182. }
  1183. foreach ($this->_fields as $fNum => $fieldInfo) {
  1184. if ($fieldInfo->isIndexed) {
  1185. $this->_norms[$fNum] = $normfFile->readBytes($this->_docCount);
  1186. }
  1187. }
  1188. } else {
  1189. $fFile = $this->openCompoundFile('.f' . $fieldNum);
  1190. $this->_norms[$fieldNum] = $fFile->readBytes($this->_docCount);
  1191. }
  1192. }
  1193. /**
  1194. * Returns normalization factor for specified documents
  1195. *
  1196. * @param integer $id
  1197. * @param string $fieldName
  1198. * @return float
  1199. */
  1200. public function norm($id, $fieldName)
  1201. {
  1202. $fieldNum = $this->getFieldNum($fieldName);
  1203. if ( !($this->_fields[$fieldNum]->isIndexed) ) {
  1204. return null;
  1205. }
  1206. if (!isset($this->_norms[$fieldNum])) {
  1207. $this->_loadNorm($fieldNum);
  1208. }
  1209. return Zend_Search_Lucene_Search_Similarity::decodeNorm( ord($this->_norms[$fieldNum][$id]) );
  1210. }
  1211. /**
  1212. * Returns norm vector, encoded in a byte string
  1213. *
  1214. * @param string $fieldName
  1215. * @return string
  1216. */
  1217. public function normVector($fieldName)
  1218. {
  1219. $fieldNum = $this->getFieldNum($fieldName);
  1220. if ($fieldNum == -1 || !($this->_fields[$fieldNum]->isIndexed)) {
  1221. $similarity = Zend_Search_Lucene_Search_Similarity::getDefault();
  1222. return str_repeat(chr($similarity->encodeNorm( $similarity->lengthNorm($fieldName, 0) )),
  1223. $this->_docCount);
  1224. }
  1225. if (!isset($this->_norms[$fieldNum])) {
  1226. $this->_loadNorm($fieldNum);
  1227. }
  1228. return $this->_norms[$fieldNum];
  1229. }
  1230. /**
  1231. * Returns true if any documents have been deleted from this index segment.
  1232. *
  1233. * @return boolean
  1234. */
  1235. public function hasDeletions()
  1236. {
  1237. return $this->_deleted !== null;
  1238. }
  1239. /**
  1240. * Returns true if segment has single norms file.
  1241. *
  1242. * @return boolean
  1243. */
  1244. public function hasSingleNormFile()
  1245. {
  1246. return $this->_hasSingleNormFile ? true : false;
  1247. }
  1248. /**
  1249. * Returns true if segment is stored using compound segment file.
  1250. *
  1251. * @return boolean
  1252. */
  1253. public function isCompound()
  1254. {
  1255. return $this->_isCompound;
  1256. }
  1257. /**
  1258. * Deletes a document from the index segment.
  1259. * $id is an internal document id
  1260. *
  1261. * @param integer
  1262. */
  1263. public function delete($id)
  1264. {
  1265. $this->_deletedDirty = true;
  1266. if (extension_loaded('bitset')) {
  1267. if ($this->_deleted === null) {
  1268. $this->_deleted = bitset_empty($id);
  1269. }
  1270. bitset_incl($this->_deleted, $id);
  1271. } else {
  1272. if ($this->_deleted === null) {
  1273. $this->_deleted = array();
  1274. }
  1275. $this->_deleted[$id] = 1;
  1276. }
  1277. }
  1278. /**
  1279. * Checks, that document is deleted
  1280. *
  1281. * @param integer
  1282. * @return boolean
  1283. */
  1284. public function isDeleted($id)
  1285. {
  1286. if ($this->_deleted === null) {
  1287. return false;
  1288. }
  1289. if (extension_loaded('bitset')) {
  1290. return bitset_in($this->_deleted, $id);
  1291. } else {
  1292. return isset($this->_deleted[$id]);
  1293. }
  1294. }
  1295. /**
  1296. * Detect latest delete generation
  1297. *
  1298. * Is actualy used from writeChanges() method or from the constructor if it's invoked from
  1299. * Index writer. In both cases index write lock is already obtained, so we shouldn't care
  1300. * about it
  1301. *
  1302. * @return integer
  1303. */
  1304. private function _detectLatestDelGen()
  1305. {
  1306. $delFileList = array();
  1307. foreach ($this->_directory->fileList() as $file) {
  1308. if ($file == $this->_name . '.del') {
  1309. // Matches <segment_name>.del file name
  1310. $delFileList[] = 0;
  1311. } else if (preg_match('/^' . $this->_name . '_([a-zA-Z0-9]+)\.del$/i', $file, $matches)) {
  1312. // Matches <segment_name>_NNN.del file names
  1313. $delFileList[] = (int)base_convert($matches[1], 36, 10);
  1314. }
  1315. }
  1316. if (count($delFileList) == 0) {
  1317. // There is no deletions file for current segment in the directory
  1318. // Set deletions file generation number to 1
  1319. return -1;
  1320. } else {
  1321. // There are some deletions files for current segment in the directory
  1322. // Set deletions file generation number to the highest nuber
  1323. return max($delFileList);
  1324. }
  1325. }
  1326. /**
  1327. * Write changes if it's necessary.
  1328. *
  1329. * This method must be invoked only from the Writer _updateSegments() method,
  1330. * so index Write lock has to be already obtained.
  1331. *
  1332. * @internal
  1333. * @throws Zend_Search_Lucene_Exceptions
  1334. */
  1335. public function writeChanges()
  1336. {
  1337. // Get new generation number
  1338. $latestDelGen = $this->_detectLatestDelGen();
  1339. if (!$this->_deletedDirty) {
  1340. // There was no deletions by current process
  1341. if ($latestDelGen == $this->_delGen) {
  1342. // Delete file hasn't been updated by any concurrent process
  1343. return;
  1344. } else if ($latestDelGen > $this->_delGen) {
  1345. // Delete file has been updated by some concurrent process
  1346. // Reload deletions file
  1347. $this->_delGen = $latestDelGen;
  1348. $this->_deleted = $this->_loadDelFile();
  1349. return;
  1350. } else {
  1351. require_once 'Zend/Search/Lucene/Exception.php';
  1352. throw new Zend_Search_Lucene_Exception('Delete file processing workflow is corrupted for the segment \'' . $this->_name . '\'.');
  1353. }
  1354. }
  1355. if ($latestDelGen > $this->_delGen) {
  1356. // Merge current deletions with latest deletions file
  1357. $this->_delGen = $latestDelGen;
  1358. $latestDelete = $this->_loadDelFile();
  1359. if (extension_loaded('bitset')) {
  1360. $this->_deleted = bitset_union($this->_deleted, $latestDelete);
  1361. } else {
  1362. $this->_deleted += $latestDelete;
  1363. }
  1364. }
  1365. if (extension_loaded('bitset')) {
  1366. $delBytes = $this->_deleted;
  1367. $bitCount = count(bitset_to_array($delBytes));
  1368. } else {
  1369. $byteCount = floor($this->_docCount/8)+1;
  1370. $delBytes = str_repeat(chr(0), $byteCount);
  1371. for ($count = 0; $count < $byteCount; $count++) {
  1372. $byte = 0;
  1373. for ($bit = 0; $bit < 8; $bit++) {
  1374. if (isset($this->_deleted[$count*8 + $bit])) {
  1375. $byte |= (1<<$bit);
  1376. }
  1377. }
  1378. $delBytes[$count] = chr($byte);
  1379. }
  1380. $bitCount = count($this->_deleted);
  1381. }
  1382. if ($this->_delGen == -1) {
  1383. // Set delete file generation number to 1
  1384. $this->_delGen = 1;
  1385. } else {
  1386. // Increase delete file generation number by 1
  1387. $this->_delGen++;
  1388. }
  1389. $delFile = $this->_directory->createFile($this->_name . '_' . base_convert($this->_delGen, 10, 36) . '.del');
  1390. $delFile->writeInt($this->_docCount);
  1391. $delFile->writeInt($bitCount);
  1392. $delFile->writeBytes($delBytes);
  1393. $this->_deletedDirty = false;
  1394. }
  1395. /**
  1396. * Term Dictionary File object for stream like terms reading
  1397. *
  1398. * @var Zend_Search_Lucene_Storage_File
  1399. */
  1400. private $_tisFile = null;
  1401. /**
  1402. * Actual offset of the .tis file data
  1403. *
  1404. * @var integer
  1405. */
  1406. private $_tisFileOffset;
  1407. /**
  1408. * Frequencies File object for stream like terms reading
  1409. *
  1410. * @var Zend_Search_Lucene_Storage_File
  1411. */
  1412. private $_frqFile = null;
  1413. /**
  1414. * Actual offset of the .frq file data
  1415. *
  1416. * @var integer
  1417. */
  1418. private $_frqFileOffset;
  1419. /**
  1420. * Positions File object for stream like terms reading
  1421. *
  1422. * @var Zend_Search_Lucene_Storage_File
  1423. */
  1424. private $_prxFile = null;
  1425. /**
  1426. * Actual offset of the .prx file in the compound file
  1427. *
  1428. * @var integer
  1429. */
  1430. private $_prxFileOffset;
  1431. /**
  1432. * Actual number of terms in term stream
  1433. *
  1434. * @var integer
  1435. */
  1436. private $_termCount = 0;
  1437. /**
  1438. * Overall number of terms in term stream
  1439. *
  1440. * @var integer
  1441. */
  1442. private $_termNum = 0;
  1443. /**
  1444. * Segment index interval
  1445. *
  1446. * @var integer
  1447. */
  1448. private $_indexInterval;
  1449. /**
  1450. * Segment skip interval
  1451. *
  1452. * @var integer
  1453. */
  1454. private $_skipInterval;
  1455. /**
  1456. * Last TermInfo in a terms stream
  1457. *
  1458. * @var Zend_Search_Lucene_Index_TermInfo
  1459. */
  1460. private $_lastTermInfo = null;
  1461. /**
  1462. * Last Term in a terms stream
  1463. *
  1464. * @var Zend_Search_Lucene_Index_Term
  1465. */
  1466. private $_lastTerm = null;
  1467. /**
  1468. * Map of the document IDs
  1469. * Used to get new docID after removing deleted documents.
  1470. * It's not very effective from memory usage point of view,
  1471. * but much more faster, then other methods
  1472. *
  1473. * @var array|null
  1474. */
  1475. private $_docMap = null;
  1476. /**
  1477. * An array of all term positions in the documents.
  1478. * Array structure: array( docId => array( pos1, pos2, ...), ...)
  1479. *
  1480. * Is set to null if term positions loading has to be skipped
  1481. *
  1482. * @var array|null
  1483. */
  1484. private $_lastTermPositions;
  1485. /**
  1486. * Terms scan mode
  1487. *
  1488. * Values:
  1489. *
  1490. * self::SM_TERMS_ONLY - terms are scanned, no additional info is retrieved
  1491. * self::SM_FULL_INFO - terms are scanned, frequency and position info is retrieved
  1492. * self::SM_MERGE_INFO - terms are scanned, frequency and position info is retrieved
  1493. * document numbers are compacted (shifted if segment has deleted documents)
  1494. *
  1495. * @var integer
  1496. */
  1497. private $_termsScanMode;
  1498. /** Scan modes */
  1499. const SM_TERMS_ONLY = 0; // terms are scanned, no additional info is retrieved
  1500. const SM_FULL_INFO = 1; // terms are scanned, frequency and position info is retrieved
  1501. const SM_MERGE_INFO = 2; // terms are scanned, frequency and position info is retrieved
  1502. // document numbers are compacted (shifted if segment contains deleted documents)
  1503. /**
  1504. * Reset terms stream
  1505. *
  1506. * $startId - id for the fist document
  1507. * $compact - remove deleted documents
  1508. *
  1509. * Returns start document id for the next segment
  1510. *
  1511. * @param integer $startId
  1512. * @param integer $mode
  1513. * @throws Zend_Search_Lucene_Exception
  1514. * @return integer
  1515. */
  1516. public function resetTermsStream(/** $startId = 0, $mode = self::SM_TERMS_ONLY */)
  1517. {
  1518. /**
  1519. * SegmentInfo->resetTermsStream() method actually takes two optional parameters:
  1520. * $startId (default value is 0)
  1521. * $mode (default value is self::SM_TERMS_ONLY)
  1522. */
  1523. $argList = func_get_args();
  1524. if (count($argList) > 2) {
  1525. require_once 'Zend/Search/Lucene/Exception.php';
  1526. throw new Zend_Search_Lucene_Exception('Wrong number of arguments');
  1527. } else if (count($argList) == 2) {
  1528. $startId = $argList[0];
  1529. $mode = $argList[1];
  1530. } else if (count($argList) == 1) {
  1531. $startId = $argList[0];
  1532. $mode = self::SM_TERMS_ONLY;
  1533. } else {
  1534. $startId = 0;
  1535. $mode = self::SM_TERMS_ONLY;
  1536. }
  1537. if ($this->_tisFile !== null) {
  1538. $this->_tisFile = null;
  1539. }
  1540. $this->_tisFile = $this->openCompoundFile('.tis', false);
  1541. $this->_tisFileOffset = $this->_tisFile->tell();
  1542. $tiVersion = $this->_tisFile->readInt();
  1543. if ($tiVersion != (int)0xFFFFFFFE /* pre-2.1 format */ &&
  1544. $tiVersion != (int)0xFFFFFFFD /* 2.1+ format */) {
  1545. require_once 'Zend/Search/Lucene/Exception.php';
  1546. throw new Zend_Search_Lucene_Exception('Wrong TermInfoFile file format');
  1547. }
  1548. $this->_termCount =
  1549. $this->_termNum = $this->_tisFile->readLong(); // Read terms count
  1550. $this->_indexInterval = $this->_tisFile->readInt(); // Read Index interval
  1551. $this->_skipInterval = $this->_tisFile->readInt(); // Read skip interval
  1552. if ($tiVersion == (int)0xFFFFFFFD /* 2.1+ format */) {
  1553. $maxSkipLevels = $this->_tisFile->readInt();
  1554. }
  1555. if ($this->_frqFile !== null) {
  1556. $this->_frqFile = null;
  1557. }
  1558. if ($this->_prxFile !== null) {
  1559. $this->_prxFile = null;
  1560. }
  1561. $this->_docMap = array();
  1562. $this->_lastTerm = new Zend_Search_Lucene_Index_Term('', -1);
  1563. $this->_lastTermInfo = new Zend_Search_Lucene_Index_TermInfo(0, 0, 0, 0);
  1564. $this->_lastTermPositions = null;
  1565. $this->_termsScanMode = $mode;
  1566. switch ($mode) {
  1567. case self::SM_TERMS_ONLY:
  1568. // Do nothing
  1569. break;
  1570. case self::SM_FULL_INFO:
  1571. // break intentionally omitted
  1572. case self::SM_MERGE_INFO:
  1573. $this->_frqFile = $this->openCompoundFile('.frq', false);
  1574. $this->_frqFileOffset = $this->_frqFile->tell();
  1575. $this->_prxFile = $this->openCompoundFile('.prx', false);
  1576. $this->_prxFileOffset = $this->_prxFile->tell();
  1577. for ($count = 0; $count < $this->_docCount; $count++) {
  1578. if (!$this->isDeleted($count)) {
  1579. $this->_docMap[$count] = $startId + (($mode == self::SM_MERGE_INFO) ? count($this->_docMap) : $count);
  1580. }
  1581. }
  1582. break;
  1583. default:
  1584. require_once 'Zend/Search/Lucene/Exception.php';
  1585. throw new Zend_Search_Lucene_Exception('Wrong terms scaning mode specified.');
  1586. break;
  1587. }
  1588. $this->nextTerm();
  1589. return $startId + (($mode == self::SM_MERGE_INFO) ? count($this->_docMap) : $this->_docCount);
  1590. }
  1591. /**
  1592. * Skip terms stream up to specified term preffix.
  1593. *
  1594. * Prefix contains fully specified field info and portion of searched term
  1595. *
  1596. * @param Zend_Search_Lucene_Index_Term $prefix
  1597. * @throws Zend_Search_Lucene_Exception
  1598. */
  1599. public function skipTo(Zend_Search_Lucene_Index_Term $prefix)
  1600. {
  1601. if ($this->_termDictionary === null) {
  1602. $this->_loadDictionaryIndex();
  1603. }
  1604. $searchField = $this->getFieldNum($prefix->field);
  1605. if ($searchField == -1) {
  1606. /**
  1607. * Field is not presented in this segment
  1608. * Go to the end of dictionary
  1609. */
  1610. $this->_tisFile = null;
  1611. $this->_frqFile = null;
  1612. $this->_prxFile = null;
  1613. $this->_lastTerm = null;
  1614. $this->_lastTermInfo = null;
  1615. $this->_lastTermPositions = null;
  1616. return;
  1617. }
  1618. $searchDicField = $this->_getFieldPosition($searchField);
  1619. // search for appropriate value in dictionary
  1620. $lowIndex = 0;
  1621. $highIndex = count($this->_termDictionary)-1;
  1622. while ($highIndex >= $lowIndex) {
  1623. // $mid = ($highIndex - $lowIndex)/2;
  1624. $mid = ($highIndex + $lowIndex) >> 1;
  1625. $midTerm = $this->_termDictionary[$mid];
  1626. $fieldNum = $this->_getFieldPosition($midTerm[0] /* field */);
  1627. $delta = $searchDicField - $fieldNum;
  1628. if ($delta == 0) {
  1629. $delta = strcmp($prefix->text, $midTerm[1] /* text */);
  1630. }
  1631. if ($delta < 0) {
  1632. $highIndex = $mid-1;
  1633. } elseif ($delta > 0) {
  1634. $lowIndex = $mid+1;
  1635. } else {
  1636. // We have reached term we are looking for
  1637. break;
  1638. }
  1639. }
  1640. if ($highIndex == -1) {
  1641. // Term is out of the dictionary range
  1642. $this->_tisFile = null;
  1643. $this->_frqFile = null;
  1644. $this->_prxFile = null;
  1645. $this->_lastTerm = null;
  1646. $this->_lastTermInfo = null;
  1647. $this->_lastTermPositions = null;
  1648. return;
  1649. }
  1650. $prevPosition = $highIndex;
  1651. $prevTerm = $this->_termDictionary[$prevPosition];
  1652. $prevTermInfo = $this->_termDictionaryInfos[$prevPosition];
  1653. if ($this->_tisFile === null) {
  1654. // The end of terms stream is reached and terms dictionary file is closed
  1655. // Perform mini-reset operation
  1656. $this->_tisFile = $this->openCompoundFile('.tis', false);
  1657. if ($this->_termsScanMode == self::SM_FULL_INFO || $this->_termsScanMode == self::SM_MERGE_INFO) {
  1658. $this->_frqFile = $this->openCompoundFile('.frq', false);
  1659. $this->_prxFile = $this->openCompoundFile('.prx', false);
  1660. }
  1661. }
  1662. $this->_tisFile->seek($this->_tisFileOffset + $prevTermInfo[4], SEEK_SET);
  1663. $this->_lastTerm = new Zend_Search_Lucene_Index_Term($prevTerm[1] /* text */,
  1664. ($prevTerm[0] == -1) ? '' : $this->_fields[$prevTerm[0] /* field */]->name);
  1665. $this->_lastTermInfo = new Zend_Search_Lucene_Index_TermInfo($prevTermInfo[0] /* docFreq */,
  1666. $prevTermInfo[1] /* freqPointer */,
  1667. $prevTermInfo[2] /* proxPointer */,
  1668. $prevTermInfo[3] /* skipOffset */);
  1669. $this->_termCount = $this->_termNum - $prevPosition*$this->_indexInterval;
  1670. if ($highIndex == 0) {
  1671. // skip start entry
  1672. $this->nextTerm();
  1673. } else if ($prefix->field == $this->_lastTerm->field && $prefix->text == $this->_lastTerm->text) {
  1674. // We got exact match in the dictionary index
  1675. if ($this->_termsScanMode == self::SM_FULL_INFO || $this->_termsScanMode == self::SM_MERGE_INFO) {
  1676. $this->_lastTermPositions = array();
  1677. $this->_frqFile->seek($this->_lastTermInfo->freqPointer + $this->_frqFileOffset, SEEK_SET);
  1678. $freqs = array(); $docId = 0;
  1679. for( $count = 0; $count < $this->_lastTermInfo->docFreq; $count++ ) {
  1680. $docDelta = $this->_frqFile->readVInt();
  1681. if( $docDelta % 2 == 1 ) {
  1682. $docId += ($docDelta-1)/2;
  1683. $freqs[ $docId ] = 1;
  1684. } else {
  1685. $docId += $docDelta/2;
  1686. $freqs[ $docId ] = $this->_frqFile->readVInt();
  1687. }
  1688. }
  1689. $this->_prxFile->seek($this->_lastTermInfo->proxPointer + $this->_prxFileOffset, SEEK_SET);
  1690. foreach ($freqs as $docId => $freq) {
  1691. $termPosition = 0; $positions = array();
  1692. for ($count = 0; $count < $freq; $count++ ) {
  1693. $termPosition += $this->_prxFile->readVInt();
  1694. $positions[] = $termPosition;
  1695. }
  1696. if (isset($this->_docMap[$docId])) {
  1697. $this->_lastTermPositions[$this->_docMap[$docId]] = $positions;
  1698. }
  1699. }
  1700. }
  1701. return;
  1702. }
  1703. // Search term matching specified prefix
  1704. while ($this->_lastTerm !== null) {
  1705. if ( strcmp($this->_lastTerm->field, $prefix->field) > 0 ||
  1706. ($prefix->field == $this->_lastTerm->field && strcmp($this->_lastTerm->text, $prefix->text) >= 0) ) {
  1707. // Current term matches or greate than the pattern
  1708. return;
  1709. }
  1710. $this->nextTerm();
  1711. }
  1712. }
  1713. /**
  1714. * Scans terms dictionary and returns next term
  1715. *
  1716. * @return Zend_Search_Lucene_Index_Term|null
  1717. */
  1718. public function nextTerm()
  1719. {
  1720. if ($this->_tisFile === null || $this->_termCount == 0) {
  1721. $this->_lastTerm = null;
  1722. $this->_lastTermInfo = null;
  1723. $this->_lastTermPositions = null;
  1724. $this->_docMap = null;
  1725. // may be necessary for "empty" segment
  1726. $this->_tisFile = null;
  1727. $this->_frqFile = null;
  1728. $this->_prxFile = null;
  1729. return null;
  1730. }
  1731. $termPrefixLength = $this->_tisFile->readVInt();
  1732. $termSuffix = $this->_tisFile->readString();
  1733. $termFieldNum = $this->_tisFile->readVInt();
  1734. $termValue = Zend_Search_Lucene_Index_Term::getPrefix($this->_lastTerm->text, $termPrefixLength) . $termSuffix;
  1735. $this->_lastTerm = new Zend_Search_Lucene_Index_Term($termValue, $this->_fields[$termFieldNum]->name);
  1736. $docFreq = $this->_tisFile->readVInt();
  1737. $freqPointer = $this->_lastTermInfo->freqPointer + $this->_tisFile->readVInt();
  1738. $proxPointer = $this->_lastTermInfo->proxPointer + $this->_tisFile->readVInt();
  1739. if ($docFreq >= $this->_skipInterval) {
  1740. $skipOffset = $this->_tisFile->readVInt();
  1741. } else {
  1742. $skipOffset = 0;
  1743. }
  1744. $this->_lastTermInfo = new Zend_Search_Lucene_Index_TermInfo($docFreq, $freqPointer, $proxPointer, $skipOffset);
  1745. if ($this->_termsScanMode == self::SM_FULL_INFO || $this->_termsScanMode == self::SM_MERGE_INFO) {
  1746. $this->_lastTermPositions = array();
  1747. $this->_frqFile->seek($this->_lastTermInfo->freqPointer + $this->_frqFileOffset, SEEK_SET);
  1748. $freqs = array(); $docId = 0;
  1749. for( $count = 0; $count < $this->_lastTermInfo->docFreq; $count++ ) {
  1750. $docDelta = $this->_frqFile->readVInt();
  1751. if( $docDelta % 2 == 1 ) {
  1752. $docId += ($docDelta-1)/2;
  1753. $freqs[ $docId ] = 1;
  1754. } else {
  1755. $docId += $docDelta/2;
  1756. $freqs[ $docId ] = $this->_frqFile->readVInt();
  1757. }
  1758. }
  1759. $this->_prxFile->seek($this->_lastTermInfo->proxPointer + $this->_prxFileOffset, SEEK_SET);
  1760. foreach ($freqs as $docId => $freq) {
  1761. $termPosition = 0; $positions = array();
  1762. for ($count = 0; $count < $freq; $count++ ) {
  1763. $termPosition += $this->_prxFile->readVInt();
  1764. $positions[] = $termPosition;
  1765. }
  1766. if (isset($this->_docMap[$docId])) {
  1767. $this->_lastTermPositions[$this->_docMap[$docId]] = $positions;
  1768. }
  1769. }
  1770. }
  1771. $this->_termCount--;
  1772. if ($this->_termCount == 0) {
  1773. $this->_tisFile = null;
  1774. $this->_frqFile = null;
  1775. $this->_prxFile = null;
  1776. }
  1777. return $this->_lastTerm;
  1778. }
  1779. /**
  1780. * Close terms stream
  1781. *
  1782. * Should be used for resources clean up if stream is not read up to the end
  1783. */
  1784. public function closeTermsStream()
  1785. {
  1786. $this->_tisFile = null;
  1787. $this->_frqFile = null;
  1788. $this->_prxFile = null;
  1789. $this->_lastTerm = null;
  1790. $this->_lastTermInfo = null;
  1791. $this->_lastTermPositions = null;
  1792. $this->_docMap = null;
  1793. }
  1794. /**
  1795. * Returns term in current position
  1796. *
  1797. * @return Zend_Search_Lucene_Index_Term|null
  1798. */
  1799. public function currentTerm()
  1800. {
  1801. return $this->_lastTerm;
  1802. }
  1803. /**
  1804. * Returns an array of all term positions in the documents.
  1805. * Return array structure: array( docId => array( pos1, pos2, ...), ...)
  1806. *
  1807. * @return array
  1808. */
  1809. public function currentTermPositions()
  1810. {
  1811. return $this->_lastTermPositions;
  1812. }
  1813. }