SegmentInfo.php 72 KB

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