Lucene.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562
  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. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /** User land classes and interfaces turned on by Zend/Search/Lucene.php file inclusion. */
  22. /** @todo Section should be removed with ZF 2.0 release as obsolete */
  23. /** Zend_Search_Lucene_Document_Html */
  24. require_once 'Zend/Search/Lucene/Document/Html.php';
  25. /** Zend_Search_Lucene_Document_Docx */
  26. require_once 'Zend/Search/Lucene/Document/Docx.php';
  27. /** Zend_Search_Lucene_Document_Pptx */
  28. require_once 'Zend/Search/Lucene/Document/Pptx.php';
  29. /** Zend_Search_Lucene_Document_Xlsx */
  30. require_once 'Zend/Search/Lucene/Document/Xlsx.php';
  31. /** Zend_Search_Lucene_Search_QueryParser */
  32. require_once 'Zend/Search/Lucene/Search/QueryParser.php';
  33. /** Zend_Search_Lucene_Search_QueryHit */
  34. require_once 'Zend/Search/Lucene/Search/QueryHit.php';
  35. /** Zend_Search_Lucene_Analysis_Analyzer */
  36. require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';
  37. /** Zend_Search_Lucene_Search_Query_Term */
  38. require_once 'Zend/Search/Lucene/Search/Query/Term.php';
  39. /** Zend_Search_Lucene_Search_Query_Phrase */
  40. require_once 'Zend/Search/Lucene/Search/Query/Phrase.php';
  41. /** Zend_Search_Lucene_Search_Query_MultiTerm */
  42. require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php';
  43. /** Zend_Search_Lucene_Search_Query_Wildcard */
  44. require_once 'Zend/Search/Lucene/Search/Query/Wildcard.php';
  45. /** Zend_Search_Lucene_Search_Query_Range */
  46. require_once 'Zend/Search/Lucene/Search/Query/Range.php';
  47. /** Zend_Search_Lucene_Search_Query_Fuzzy */
  48. require_once 'Zend/Search/Lucene/Search/Query/Fuzzy.php';
  49. /** Zend_Search_Lucene_Search_Query_Boolean */
  50. require_once 'Zend/Search/Lucene/Search/Query/Boolean.php';
  51. /** Zend_Search_Lucene_Search_Query_Empty */
  52. require_once 'Zend/Search/Lucene/Search/Query/Empty.php';
  53. /** Zend_Search_Lucene_Search_Query_Insignificant */
  54. require_once 'Zend/Search/Lucene/Search/Query/Insignificant.php';
  55. /** Internally used classes */
  56. /** Zend_Search_Lucene_Interface */
  57. require_once 'Zend/Search/Lucene/Interface.php';
  58. /** Zend_Search_Lucene_Index_SegmentInfo */
  59. require_once 'Zend/Search/Lucene/Index/SegmentInfo.php';
  60. /** Zend_Search_Lucene_LockManager */
  61. require_once 'Zend/Search/Lucene/LockManager.php';
  62. /**
  63. * @category Zend
  64. * @package Zend_Search_Lucene
  65. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  66. * @license http://framework.zend.com/license/new-bsd New BSD License
  67. */
  68. class Zend_Search_Lucene implements Zend_Search_Lucene_Interface
  69. {
  70. /**
  71. * Default field name for search
  72. *
  73. * Null means search through all fields
  74. *
  75. * @var string
  76. */
  77. private static $_defaultSearchField = null;
  78. /**
  79. * Result set limit
  80. *
  81. * 0 means no limit
  82. *
  83. * @var integer
  84. */
  85. private static $_resultSetLimit = 0;
  86. /**
  87. * Terms per query limit
  88. *
  89. * 0 means no limit
  90. *
  91. * @var integer
  92. */
  93. private static $_termsPerQueryLimit = 1024;
  94. /**
  95. * File system adapter.
  96. *
  97. * @var Zend_Search_Lucene_Storage_Directory
  98. */
  99. private $_directory = null;
  100. /**
  101. * File system adapter closing option
  102. *
  103. * @var boolean
  104. */
  105. private $_closeDirOnExit = true;
  106. /**
  107. * Writer for this index, not instantiated unless required.
  108. *
  109. * @var Zend_Search_Lucene_Index_Writer
  110. */
  111. private $_writer = null;
  112. /**
  113. * Array of Zend_Search_Lucene_Index_SegmentInfo objects for current version of index.
  114. *
  115. * @var array Zend_Search_Lucene_Index_SegmentInfo
  116. */
  117. private $_segmentInfos = array();
  118. /**
  119. * Number of documents in this index.
  120. *
  121. * @var integer
  122. */
  123. private $_docCount = 0;
  124. /**
  125. * Flag for index changes
  126. *
  127. * @var boolean
  128. */
  129. private $_hasChanges = false;
  130. /**
  131. * Signal, that index is already closed, changes are fixed and resources are cleaned up
  132. *
  133. * @var boolean
  134. */
  135. private $_closed = false;
  136. /**
  137. * Number of references to the index object
  138. *
  139. * @var integer
  140. */
  141. private $_refCount = 0;
  142. /**
  143. * Current segment generation
  144. *
  145. * @var integer
  146. */
  147. private $_generation;
  148. const FORMAT_PRE_2_1 = 0;
  149. const FORMAT_2_1 = 1;
  150. const FORMAT_2_3 = 2;
  151. /**
  152. * Index format version
  153. *
  154. * @var integer
  155. */
  156. private $_formatVersion;
  157. /**
  158. * Create index
  159. *
  160. * @param mixed $directory
  161. * @return Zend_Search_Lucene_Interface
  162. */
  163. public static function create($directory)
  164. {
  165. /** Zend_Search_Lucene_Proxy */
  166. require_once 'Zend/Search/Lucene/Proxy.php';
  167. return new Zend_Search_Lucene_Proxy(new Zend_Search_Lucene($directory, true));
  168. }
  169. /**
  170. * Open index
  171. *
  172. * @param mixed $directory
  173. * @return Zend_Search_Lucene_Interface
  174. */
  175. public static function open($directory)
  176. {
  177. /** Zend_Search_Lucene_Proxy */
  178. require_once 'Zend/Search/Lucene/Proxy.php';
  179. return new Zend_Search_Lucene_Proxy(new Zend_Search_Lucene($directory, false));
  180. }
  181. /** Generation retrieving counter */
  182. const GENERATION_RETRIEVE_COUNT = 10;
  183. /** Pause between generation retrieving attempts in milliseconds */
  184. const GENERATION_RETRIEVE_PAUSE = 50;
  185. /**
  186. * Get current generation number
  187. *
  188. * Returns generation number
  189. * 0 means pre-2.1 index format
  190. * -1 means there are no segments files.
  191. *
  192. * @param Zend_Search_Lucene_Storage_Directory $directory
  193. * @return integer
  194. * @throws Zend_Search_Lucene_Exception
  195. */
  196. public static function getActualGeneration(Zend_Search_Lucene_Storage_Directory $directory)
  197. {
  198. /**
  199. * Zend_Search_Lucene uses segments.gen file to retrieve current generation number
  200. *
  201. * Apache Lucene index format documentation mentions this method only as a fallback method
  202. *
  203. * Nevertheless we use it according to the performance considerations
  204. *
  205. * @todo check if we can use some modification of Apache Lucene generation determination algorithm
  206. * without performance problems
  207. */
  208. require_once 'Zend/Search/Lucene/Exception.php';
  209. try {
  210. for ($count = 0; $count < self::GENERATION_RETRIEVE_COUNT; $count++) {
  211. // Try to get generation file
  212. $genFile = $directory->getFileObject('segments.gen', false);
  213. $format = $genFile->readInt();
  214. if ($format != (int)0xFFFFFFFE) {
  215. throw new Zend_Search_Lucene_Exception('Wrong segments.gen file format');
  216. }
  217. $gen1 = $genFile->readLong();
  218. $gen2 = $genFile->readLong();
  219. if ($gen1 == $gen2) {
  220. return $gen1;
  221. }
  222. usleep(self::GENERATION_RETRIEVE_PAUSE * 1000);
  223. }
  224. // All passes are failed
  225. throw new Zend_Search_Lucene_Exception('Index is under processing now');
  226. } catch (Zend_Search_Lucene_Exception $e) {
  227. if (strpos($e->getMessage(), 'is not readable') !== false) {
  228. try {
  229. // Try to open old style segments file
  230. $segmentsFile = $directory->getFileObject('segments', false);
  231. // It's pre-2.1 index
  232. return 0;
  233. } catch (Zend_Search_Lucene_Exception $e) {
  234. if (strpos($e->getMessage(), 'is not readable') !== false) {
  235. return -1;
  236. } else {
  237. throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e);
  238. }
  239. }
  240. } else {
  241. throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e);
  242. }
  243. }
  244. return -1;
  245. }
  246. /**
  247. * Get segments file name
  248. *
  249. * @param integer $generation
  250. * @return string
  251. */
  252. public static function getSegmentFileName($generation)
  253. {
  254. if ($generation == 0) {
  255. return 'segments';
  256. }
  257. return 'segments_' . base_convert($generation, 10, 36);
  258. }
  259. /**
  260. * Get index format version
  261. *
  262. * @return integer
  263. */
  264. public function getFormatVersion()
  265. {
  266. return $this->_formatVersion;
  267. }
  268. /**
  269. * Set index format version.
  270. * Index is converted to this format at the nearest upfdate time
  271. *
  272. * @param int $formatVersion
  273. * @throws Zend_Search_Lucene_Exception
  274. */
  275. public function setFormatVersion($formatVersion)
  276. {
  277. if ($formatVersion != self::FORMAT_PRE_2_1 &&
  278. $formatVersion != self::FORMAT_2_1 &&
  279. $formatVersion != self::FORMAT_2_3) {
  280. require_once 'Zend/Search/Lucene/Exception.php';
  281. throw new Zend_Search_Lucene_Exception('Unsupported index format');
  282. }
  283. $this->_formatVersion = $formatVersion;
  284. }
  285. /**
  286. * Read segments file for pre-2.1 Lucene index format
  287. *
  288. * @throws Zend_Search_Lucene_Exception
  289. */
  290. private function _readPre21SegmentsFile()
  291. {
  292. $segmentsFile = $this->_directory->getFileObject('segments');
  293. $format = $segmentsFile->readInt();
  294. if ($format != (int)0xFFFFFFFF) {
  295. require_once 'Zend/Search/Lucene/Exception.php';
  296. throw new Zend_Search_Lucene_Exception('Wrong segments file format');
  297. }
  298. // read version
  299. $segmentsFile->readLong();
  300. // read segment name counter
  301. $segmentsFile->readInt();
  302. $segments = $segmentsFile->readInt();
  303. $this->_docCount = 0;
  304. // read segmentInfos
  305. for ($count = 0; $count < $segments; $count++) {
  306. $segName = $segmentsFile->readString();
  307. $segSize = $segmentsFile->readInt();
  308. $this->_docCount += $segSize;
  309. $this->_segmentInfos[$segName] =
  310. new Zend_Search_Lucene_Index_SegmentInfo($this->_directory,
  311. $segName,
  312. $segSize);
  313. }
  314. // Use 2.1 as a target version. Index will be reorganized at update time.
  315. $this->_formatVersion = self::FORMAT_2_1;
  316. }
  317. /**
  318. * Read segments file
  319. *
  320. * @throws Zend_Search_Lucene_Exception
  321. */
  322. private function _readSegmentsFile()
  323. {
  324. $segmentsFile = $this->_directory->getFileObject(self::getSegmentFileName($this->_generation));
  325. $format = $segmentsFile->readInt();
  326. if ($format == (int)0xFFFFFFFC) {
  327. $this->_formatVersion = self::FORMAT_2_3;
  328. } else if ($format == (int)0xFFFFFFFD) {
  329. $this->_formatVersion = self::FORMAT_2_1;
  330. } else {
  331. require_once 'Zend/Search/Lucene/Exception.php';
  332. throw new Zend_Search_Lucene_Exception('Unsupported segments file format');
  333. }
  334. // read version
  335. $segmentsFile->readLong();
  336. // read segment name counter
  337. $segmentsFile->readInt();
  338. $segments = $segmentsFile->readInt();
  339. $this->_docCount = 0;
  340. // read segmentInfos
  341. for ($count = 0; $count < $segments; $count++) {
  342. $segName = $segmentsFile->readString();
  343. $segSize = $segmentsFile->readInt();
  344. // 2.1+ specific properties
  345. $delGen = $segmentsFile->readLong();
  346. if ($this->_formatVersion == self::FORMAT_2_3) {
  347. $docStoreOffset = $segmentsFile->readInt();
  348. if ($docStoreOffset != (int)0xFFFFFFFF) {
  349. $docStoreSegment = $segmentsFile->readString();
  350. $docStoreIsCompoundFile = $segmentsFile->readByte();
  351. $docStoreOptions = array('offset' => $docStoreOffset,
  352. 'segment' => $docStoreSegment,
  353. 'isCompound' => ($docStoreIsCompoundFile == 1));
  354. } else {
  355. $docStoreOptions = null;
  356. }
  357. } else {
  358. $docStoreOptions = null;
  359. }
  360. $hasSingleNormFile = $segmentsFile->readByte();
  361. $numField = $segmentsFile->readInt();
  362. $normGens = array();
  363. if ($numField != (int)0xFFFFFFFF) {
  364. for ($count1 = 0; $count1 < $numField; $count1++) {
  365. $normGens[] = $segmentsFile->readLong();
  366. }
  367. require_once 'Zend/Search/Lucene/Exception.php';
  368. throw new Zend_Search_Lucene_Exception('Separate norm files are not supported. Optimize index to use it with Zend_Search_Lucene.');
  369. }
  370. $isCompoundByte = $segmentsFile->readByte();
  371. if ($isCompoundByte == 0xFF) {
  372. // The segment is not a compound file
  373. $isCompound = false;
  374. } else if ($isCompoundByte == 0x00) {
  375. // The status is unknown
  376. $isCompound = null;
  377. } else if ($isCompoundByte == 0x01) {
  378. // The segment is a compound file
  379. $isCompound = true;
  380. }
  381. $this->_docCount += $segSize;
  382. $this->_segmentInfos[$segName] =
  383. new Zend_Search_Lucene_Index_SegmentInfo($this->_directory,
  384. $segName,
  385. $segSize,
  386. $delGen,
  387. $docStoreOptions,
  388. $hasSingleNormFile,
  389. $isCompound);
  390. }
  391. }
  392. /**
  393. * Opens the index.
  394. *
  395. * IndexReader constructor needs Directory as a parameter. It should be
  396. * a string with a path to the index folder or a Directory object.
  397. *
  398. * @param Zend_Search_Lucene_Storage_Directory_Filesystem|string $directory
  399. * @throws Zend_Search_Lucene_Exception
  400. */
  401. public function __construct($directory = null, $create = false)
  402. {
  403. if ($directory === null) {
  404. require_once 'Zend/Search/Lucene/Exception.php';
  405. throw new Zend_Search_Exception('No index directory specified');
  406. }
  407. if (is_string($directory)) {
  408. require_once 'Zend/Search/Lucene/Storage/Directory/Filesystem.php';
  409. $this->_directory = new Zend_Search_Lucene_Storage_Directory_Filesystem($directory);
  410. $this->_closeDirOnExit = true;
  411. } else {
  412. $this->_directory = $directory;
  413. $this->_closeDirOnExit = false;
  414. }
  415. $this->_segmentInfos = array();
  416. // Mark index as "under processing" to prevent other processes from premature index cleaning
  417. Zend_Search_Lucene_LockManager::obtainReadLock($this->_directory);
  418. $this->_generation = self::getActualGeneration($this->_directory);
  419. if ($create) {
  420. require_once 'Zend/Search/Lucene/Exception.php';
  421. try {
  422. Zend_Search_Lucene_LockManager::obtainWriteLock($this->_directory);
  423. } catch (Zend_Search_Lucene_Exception $e) {
  424. Zend_Search_Lucene_LockManager::releaseReadLock($this->_directory);
  425. if (strpos($e->getMessage(), 'Can\'t obtain exclusive index lock') === false) {
  426. throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e);
  427. } else {
  428. throw new Zend_Search_Lucene_Exception('Can\'t create index. It\'s under processing now', 0, $e);
  429. }
  430. }
  431. if ($this->_generation == -1) {
  432. // Directory doesn't contain existing index, start from 1
  433. $this->_generation = 1;
  434. $nameCounter = 0;
  435. } else {
  436. // Directory contains existing index
  437. $segmentsFile = $this->_directory->getFileObject(self::getSegmentFileName($this->_generation));
  438. $segmentsFile->seek(12); // 12 = 4 (int, file format marker) + 8 (long, index version)
  439. $nameCounter = $segmentsFile->readInt();
  440. $this->_generation++;
  441. }
  442. require_once 'Zend/Search/Lucene/Index/Writer.php';
  443. Zend_Search_Lucene_Index_Writer::createIndex($this->_directory, $this->_generation, $nameCounter);
  444. Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory);
  445. }
  446. if ($this->_generation == -1) {
  447. require_once 'Zend/Search/Lucene/Exception.php';
  448. throw new Zend_Search_Lucene_Exception('Index doesn\'t exists in the specified directory.');
  449. } else if ($this->_generation == 0) {
  450. $this->_readPre21SegmentsFile();
  451. } else {
  452. $this->_readSegmentsFile();
  453. }
  454. }
  455. /**
  456. * Close current index and free resources
  457. */
  458. private function _close()
  459. {
  460. if ($this->_closed) {
  461. // index is already closed and resources are cleaned up
  462. return;
  463. }
  464. $this->commit();
  465. // Release "under processing" flag
  466. Zend_Search_Lucene_LockManager::releaseReadLock($this->_directory);
  467. if ($this->_closeDirOnExit) {
  468. $this->_directory->close();
  469. }
  470. $this->_directory = null;
  471. $this->_writer = null;
  472. $this->_segmentInfos = null;
  473. $this->_closed = true;
  474. }
  475. /**
  476. * Add reference to the index object
  477. *
  478. * @internal
  479. */
  480. public function addReference()
  481. {
  482. $this->_refCount++;
  483. }
  484. /**
  485. * Remove reference from the index object
  486. *
  487. * When reference count becomes zero, index is closed and resources are cleaned up
  488. *
  489. * @internal
  490. */
  491. public function removeReference()
  492. {
  493. $this->_refCount--;
  494. if ($this->_refCount == 0) {
  495. $this->_close();
  496. }
  497. }
  498. /**
  499. * Object destructor
  500. */
  501. public function __destruct()
  502. {
  503. $this->_close();
  504. }
  505. /**
  506. * Returns an instance of Zend_Search_Lucene_Index_Writer for the index
  507. *
  508. * @return Zend_Search_Lucene_Index_Writer
  509. */
  510. private function _getIndexWriter()
  511. {
  512. if ($this->_writer === null) {
  513. require_once 'Zend/Search/Lucene/Index/Writer.php';
  514. $this->_writer = new Zend_Search_Lucene_Index_Writer($this->_directory,
  515. $this->_segmentInfos,
  516. $this->_formatVersion);
  517. }
  518. return $this->_writer;
  519. }
  520. /**
  521. * Returns the Zend_Search_Lucene_Storage_Directory instance for this index.
  522. *
  523. * @return Zend_Search_Lucene_Storage_Directory
  524. */
  525. public function getDirectory()
  526. {
  527. return $this->_directory;
  528. }
  529. /**
  530. * Returns the total number of documents in this index (including deleted documents).
  531. *
  532. * @return integer
  533. */
  534. public function count()
  535. {
  536. return $this->_docCount;
  537. }
  538. /**
  539. * Returns one greater than the largest possible document number.
  540. * This may be used to, e.g., determine how big to allocate a structure which will have
  541. * an element for every document number in an index.
  542. *
  543. * @return integer
  544. */
  545. public function maxDoc()
  546. {
  547. return $this->count();
  548. }
  549. /**
  550. * Returns the total number of non-deleted documents in this index.
  551. *
  552. * @return integer
  553. */
  554. public function numDocs()
  555. {
  556. $numDocs = 0;
  557. foreach ($this->_segmentInfos as $segmentInfo) {
  558. $numDocs += $segmentInfo->numDocs();
  559. }
  560. return $numDocs;
  561. }
  562. /**
  563. * Checks, that document is deleted
  564. *
  565. * @param integer $id
  566. * @return boolean
  567. * @throws Zend_Search_Lucene_Exception Exception is thrown if $id is out of the range
  568. */
  569. public function isDeleted($id)
  570. {
  571. if ($id >= $this->_docCount) {
  572. require_once 'Zend/Search/Lucene/Exception.php';
  573. throw new Zend_Search_Lucene_Exception('Document id is out of the range.');
  574. }
  575. $segmentStartId = 0;
  576. foreach ($this->_segmentInfos as $segmentInfo) {
  577. if ($segmentStartId + $segmentInfo->count() > $id) {
  578. break;
  579. }
  580. $segmentStartId += $segmentInfo->count();
  581. }
  582. return $segmentInfo->isDeleted($id - $segmentStartId);
  583. }
  584. /**
  585. * Set default search field.
  586. *
  587. * Null means, that search is performed through all fields by default
  588. *
  589. * Default value is null
  590. *
  591. * @param string $fieldName
  592. */
  593. public static function setDefaultSearchField($fieldName)
  594. {
  595. self::$_defaultSearchField = $fieldName;
  596. }
  597. /**
  598. * Get default search field.
  599. *
  600. * Null means, that search is performed through all fields by default
  601. *
  602. * @return string
  603. */
  604. public static function getDefaultSearchField()
  605. {
  606. return self::$_defaultSearchField;
  607. }
  608. /**
  609. * Set result set limit.
  610. *
  611. * 0 (default) means no limit
  612. *
  613. * @param integer $limit
  614. */
  615. public static function setResultSetLimit($limit)
  616. {
  617. self::$_resultSetLimit = $limit;
  618. }
  619. /**
  620. * Get result set limit.
  621. *
  622. * 0 means no limit
  623. *
  624. * @return integer
  625. */
  626. public static function getResultSetLimit()
  627. {
  628. return self::$_resultSetLimit;
  629. }
  630. /**
  631. * Set terms per query limit.
  632. *
  633. * 0 means no limit
  634. *
  635. * @param integer $limit
  636. */
  637. public static function setTermsPerQueryLimit($limit)
  638. {
  639. self::$_termsPerQueryLimit = $limit;
  640. }
  641. /**
  642. * Get result set limit.
  643. *
  644. * 0 (default) means no limit
  645. *
  646. * @return integer
  647. */
  648. public static function getTermsPerQueryLimit()
  649. {
  650. return self::$_termsPerQueryLimit;
  651. }
  652. /**
  653. * Retrieve index maxBufferedDocs option
  654. *
  655. * maxBufferedDocs is a minimal number of documents required before
  656. * the buffered in-memory documents are written into a new Segment
  657. *
  658. * Default value is 10
  659. *
  660. * @return integer
  661. */
  662. public function getMaxBufferedDocs()
  663. {
  664. return $this->_getIndexWriter()->maxBufferedDocs;
  665. }
  666. /**
  667. * Set index maxBufferedDocs option
  668. *
  669. * maxBufferedDocs is a minimal number of documents required before
  670. * the buffered in-memory documents are written into a new Segment
  671. *
  672. * Default value is 10
  673. *
  674. * @param integer $maxBufferedDocs
  675. */
  676. public function setMaxBufferedDocs($maxBufferedDocs)
  677. {
  678. $this->_getIndexWriter()->maxBufferedDocs = $maxBufferedDocs;
  679. }
  680. /**
  681. * Retrieve index maxMergeDocs option
  682. *
  683. * maxMergeDocs is a largest number of documents ever merged by addDocument().
  684. * Small values (e.g., less than 10,000) are best for interactive indexing,
  685. * as this limits the length of pauses while indexing to a few seconds.
  686. * Larger values are best for batched indexing and speedier searches.
  687. *
  688. * Default value is PHP_INT_MAX
  689. *
  690. * @return integer
  691. */
  692. public function getMaxMergeDocs()
  693. {
  694. return $this->_getIndexWriter()->maxMergeDocs;
  695. }
  696. /**
  697. * Set index maxMergeDocs option
  698. *
  699. * maxMergeDocs is a largest number of documents ever merged by addDocument().
  700. * Small values (e.g., less than 10,000) are best for interactive indexing,
  701. * as this limits the length of pauses while indexing to a few seconds.
  702. * Larger values are best for batched indexing and speedier searches.
  703. *
  704. * Default value is PHP_INT_MAX
  705. *
  706. * @param integer $maxMergeDocs
  707. */
  708. public function setMaxMergeDocs($maxMergeDocs)
  709. {
  710. $this->_getIndexWriter()->maxMergeDocs = $maxMergeDocs;
  711. }
  712. /**
  713. * Retrieve index mergeFactor option
  714. *
  715. * mergeFactor determines how often segment indices are merged by addDocument().
  716. * With smaller values, less RAM is used while indexing,
  717. * and searches on unoptimized indices are faster,
  718. * but indexing speed is slower.
  719. * With larger values, more RAM is used during indexing,
  720. * and while searches on unoptimized indices are slower,
  721. * indexing is faster.
  722. * Thus larger values (> 10) are best for batch index creation,
  723. * and smaller values (< 10) for indices that are interactively maintained.
  724. *
  725. * Default value is 10
  726. *
  727. * @return integer
  728. */
  729. public function getMergeFactor()
  730. {
  731. return $this->_getIndexWriter()->mergeFactor;
  732. }
  733. /**
  734. * Set index mergeFactor option
  735. *
  736. * mergeFactor determines how often segment indices are merged by addDocument().
  737. * With smaller values, less RAM is used while indexing,
  738. * and searches on unoptimized indices are faster,
  739. * but indexing speed is slower.
  740. * With larger values, more RAM is used during indexing,
  741. * and while searches on unoptimized indices are slower,
  742. * indexing is faster.
  743. * Thus larger values (> 10) are best for batch index creation,
  744. * and smaller values (< 10) for indices that are interactively maintained.
  745. *
  746. * Default value is 10
  747. *
  748. * @param integer $maxMergeDocs
  749. */
  750. public function setMergeFactor($mergeFactor)
  751. {
  752. $this->_getIndexWriter()->mergeFactor = $mergeFactor;
  753. }
  754. /**
  755. * Performs a query against the index and returns an array
  756. * of Zend_Search_Lucene_Search_QueryHit objects.
  757. * Input is a string or Zend_Search_Lucene_Search_Query.
  758. *
  759. * @param Zend_Search_Lucene_Search_QueryParser|string $query
  760. * @return array Zend_Search_Lucene_Search_QueryHit
  761. * @throws Zend_Search_Lucene_Exception
  762. */
  763. public function find($query)
  764. {
  765. if (is_string($query)) {
  766. require_once 'Zend/Search/Lucene/Search/QueryParser.php';
  767. $query = Zend_Search_Lucene_Search_QueryParser::parse($query);
  768. }
  769. if (!$query instanceof Zend_Search_Lucene_Search_Query) {
  770. require_once 'Zend/Search/Lucene/Exception.php';
  771. throw new Zend_Search_Lucene_Exception('Query must be a string or Zend_Search_Lucene_Search_Query object');
  772. }
  773. $this->commit();
  774. $hits = array();
  775. $scores = array();
  776. $ids = array();
  777. $query = $query->rewrite($this)->optimize($this);
  778. $query->execute($this);
  779. $topScore = 0;
  780. /** Zend_Search_Lucene_Search_QueryHit */
  781. require_once 'Zend/Search/Lucene/Search/QueryHit.php';
  782. foreach ($query->matchedDocs() as $id => $num) {
  783. $docScore = $query->score($id, $this);
  784. if( $docScore != 0 ) {
  785. $hit = new Zend_Search_Lucene_Search_QueryHit($this);
  786. $hit->id = $id;
  787. $hit->score = $docScore;
  788. $hits[] = $hit;
  789. $ids[] = $id;
  790. $scores[] = $docScore;
  791. if ($docScore > $topScore) {
  792. $topScore = $docScore;
  793. }
  794. }
  795. if (self::$_resultSetLimit != 0 && count($hits) >= self::$_resultSetLimit) {
  796. break;
  797. }
  798. }
  799. if (count($hits) == 0) {
  800. // skip sorting, which may cause a error on empty index
  801. return array();
  802. }
  803. if ($topScore > 1) {
  804. foreach ($hits as $hit) {
  805. $hit->score /= $topScore;
  806. }
  807. }
  808. if (func_num_args() == 1) {
  809. // sort by scores
  810. array_multisort($scores, SORT_DESC, SORT_NUMERIC,
  811. $ids, SORT_ASC, SORT_NUMERIC,
  812. $hits);
  813. } else {
  814. // sort by given field names
  815. $argList = func_get_args();
  816. $fieldNames = $this->getFieldNames();
  817. $sortArgs = array();
  818. // PHP 5.3 now expects all arguments to array_multisort be passed by
  819. // reference (if it's invoked through call_user_func_array());
  820. // since constants can't be passed by reference, create some placeholder variables.
  821. $sortReg = SORT_REGULAR;
  822. $sortAsc = SORT_ASC;
  823. $sortNum = SORT_NUMERIC;
  824. $sortFieldValues = array();
  825. require_once 'Zend/Search/Lucene/Exception.php';
  826. for ($count = 1; $count < count($argList); $count++) {
  827. $fieldName = $argList[$count];
  828. if (!is_string($fieldName)) {
  829. throw new Zend_Search_Lucene_Exception('Field name must be a string.');
  830. }
  831. if (strtolower($fieldName) == 'score') {
  832. $sortArgs[] = &$scores;
  833. } else {
  834. if (!in_array($fieldName, $fieldNames)) {
  835. throw new Zend_Search_Lucene_Exception('Wrong field name.');
  836. }
  837. if (!isset($sortFieldValues[$fieldName])) {
  838. $valuesArray = array();
  839. foreach ($hits as $hit) {
  840. try {
  841. $value = $hit->getDocument()->getFieldValue($fieldName);
  842. } catch (Zend_Search_Lucene_Exception $e) {
  843. if (strpos($e->getMessage(), 'not found') === false) {
  844. throw new Zend_Search_Lucene_Exception($e->getMessage(), $e->getCode(), $e);
  845. } else {
  846. $value = null;
  847. }
  848. }
  849. $valuesArray[] = $value;
  850. }
  851. // Collect loaded values in $sortFieldValues
  852. // Required for PHP 5.3 which translates references into values when source
  853. // variable is destroyed
  854. $sortFieldValues[$fieldName] = $valuesArray;
  855. }
  856. $sortArgs[] = &$sortFieldValues[$fieldName];
  857. }
  858. if ($count + 1 < count($argList) && is_integer($argList[$count+1])) {
  859. $count++;
  860. $sortArgs[] = &$argList[$count];
  861. if ($count + 1 < count($argList) && is_integer($argList[$count+1])) {
  862. $count++;
  863. $sortArgs[] = &$argList[$count];
  864. } else {
  865. if ($argList[$count] == SORT_ASC || $argList[$count] == SORT_DESC) {
  866. $sortArgs[] = &$sortReg;
  867. } else {
  868. $sortArgs[] = &$sortAsc;
  869. }
  870. }
  871. } else {
  872. $sortArgs[] = &$sortAsc;
  873. $sortArgs[] = &$sortReg;
  874. }
  875. }
  876. // Sort by id's if values are equal
  877. $sortArgs[] = &$ids;
  878. $sortArgs[] = &$sortAsc;
  879. $sortArgs[] = &$sortNum;
  880. // Array to be sorted
  881. $sortArgs[] = &$hits;
  882. // Do sort
  883. call_user_func_array('array_multisort', $sortArgs);
  884. }
  885. return $hits;
  886. }
  887. /**
  888. * Returns a list of all unique field names that exist in this index.
  889. *
  890. * @param boolean $indexed
  891. * @return array
  892. */
  893. public function getFieldNames($indexed = false)
  894. {
  895. $result = array();
  896. foreach( $this->_segmentInfos as $segmentInfo ) {
  897. $result = array_merge($result, $segmentInfo->getFields($indexed));
  898. }
  899. return $result;
  900. }
  901. /**
  902. * Returns a Zend_Search_Lucene_Document object for the document
  903. * number $id in this index.
  904. *
  905. * @param integer|Zend_Search_Lucene_Search_QueryHit $id
  906. * @return Zend_Search_Lucene_Document
  907. * @throws Zend_Search_Lucene_Exception Exception is thrown if $id is out of the range
  908. */
  909. public function getDocument($id)
  910. {
  911. if ($id instanceof Zend_Search_Lucene_Search_QueryHit) {
  912. /* @var $id Zend_Search_Lucene_Search_QueryHit */
  913. $id = $id->id;
  914. }
  915. if ($id >= $this->_docCount) {
  916. require_once 'Zend/Search/Lucene/Exception.php';
  917. throw new Zend_Search_Lucene_Exception('Document id is out of the range.');
  918. }
  919. $segmentStartId = 0;
  920. foreach ($this->_segmentInfos as $segmentInfo) {
  921. if ($segmentStartId + $segmentInfo->count() > $id) {
  922. break;
  923. }
  924. $segmentStartId += $segmentInfo->count();
  925. }
  926. $fdxFile = $segmentInfo->openCompoundFile('.fdx');
  927. $fdxFile->seek(($id-$segmentStartId)*8, SEEK_CUR);
  928. $fieldValuesPosition = $fdxFile->readLong();
  929. $fdtFile = $segmentInfo->openCompoundFile('.fdt');
  930. $fdtFile->seek($fieldValuesPosition, SEEK_CUR);
  931. $fieldCount = $fdtFile->readVInt();
  932. $doc = new Zend_Search_Lucene_Document();
  933. for ($count = 0; $count < $fieldCount; $count++) {
  934. $fieldNum = $fdtFile->readVInt();
  935. $bits = $fdtFile->readByte();
  936. $fieldInfo = $segmentInfo->getField($fieldNum);
  937. if (!($bits & 2)) { // Text data
  938. $field = new Zend_Search_Lucene_Field($fieldInfo->name,
  939. $fdtFile->readString(),
  940. 'UTF-8',
  941. true,
  942. $fieldInfo->isIndexed,
  943. $bits & 1 );
  944. } else { // Binary data
  945. $field = new Zend_Search_Lucene_Field($fieldInfo->name,
  946. $fdtFile->readBinary(),
  947. '',
  948. true,
  949. $fieldInfo->isIndexed,
  950. $bits & 1,
  951. true );
  952. }
  953. $doc->addField($field);
  954. }
  955. return $doc;
  956. }
  957. /**
  958. * Returns true if index contain documents with specified term.
  959. *
  960. * Is used for query optimization.
  961. *
  962. * @param Zend_Search_Lucene_Index_Term $term
  963. * @return boolean
  964. */
  965. public function hasTerm(Zend_Search_Lucene_Index_Term $term)
  966. {
  967. foreach ($this->_segmentInfos as $segInfo) {
  968. if ($segInfo->getTermInfo($term) !== null) {
  969. return true;
  970. }
  971. }
  972. return false;
  973. }
  974. /**
  975. * Returns IDs of all documents containing term.
  976. *
  977. * @param Zend_Search_Lucene_Index_Term $term
  978. * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
  979. * @return array
  980. */
  981. public function termDocs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null)
  982. {
  983. $subResults = array();
  984. $segmentStartDocId = 0;
  985. foreach ($this->_segmentInfos as $segmentInfo) {
  986. $subResults[] = $segmentInfo->termDocs($term, $segmentStartDocId, $docsFilter);
  987. $segmentStartDocId += $segmentInfo->count();
  988. }
  989. if (count($subResults) == 0) {
  990. return array();
  991. } else if (count($subResults) == 1) {
  992. // Index is optimized (only one segment)
  993. // Do not perform array reindexing
  994. return reset($subResults);
  995. } else {
  996. $result = call_user_func_array('array_merge', $subResults);
  997. }
  998. return $result;
  999. }
  1000. /**
  1001. * Returns documents filter for all documents containing term.
  1002. *
  1003. * It performs the same operation as termDocs, but return result as
  1004. * Zend_Search_Lucene_Index_DocsFilter object
  1005. *
  1006. * @param Zend_Search_Lucene_Index_Term $term
  1007. * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
  1008. * @return Zend_Search_Lucene_Index_DocsFilter
  1009. */
  1010. public function termDocsFilter(Zend_Search_Lucene_Index_Term $term, $docsFilter = null)
  1011. {
  1012. $segmentStartDocId = 0;
  1013. $result = new Zend_Search_Lucene_Index_DocsFilter();
  1014. foreach ($this->_segmentInfos as $segmentInfo) {
  1015. $subResults[] = $segmentInfo->termDocs($term, $segmentStartDocId, $docsFilter);
  1016. $segmentStartDocId += $segmentInfo->count();
  1017. }
  1018. if (count($subResults) == 0) {
  1019. return array();
  1020. } else if (count($subResults) == 1) {
  1021. // Index is optimized (only one segment)
  1022. // Do not perform array reindexing
  1023. return reset($subResults);
  1024. } else {
  1025. $result = call_user_func_array('array_merge', $subResults);
  1026. }
  1027. return $result;
  1028. }
  1029. /**
  1030. * Returns an array of all term freqs.
  1031. * Result array structure: array(docId => freq, ...)
  1032. *
  1033. * @param Zend_Search_Lucene_Index_Term $term
  1034. * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
  1035. * @return integer
  1036. */
  1037. public function termFreqs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null)
  1038. {
  1039. $result = array();
  1040. $segmentStartDocId = 0;
  1041. foreach ($this->_segmentInfos as $segmentInfo) {
  1042. $result += $segmentInfo->termFreqs($term, $segmentStartDocId, $docsFilter);
  1043. $segmentStartDocId += $segmentInfo->count();
  1044. }
  1045. return $result;
  1046. }
  1047. /**
  1048. * Returns an array of all term positions in the documents.
  1049. * Result array structure: array(docId => array(pos1, pos2, ...), ...)
  1050. *
  1051. * @param Zend_Search_Lucene_Index_Term $term
  1052. * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
  1053. * @return array
  1054. */
  1055. public function termPositions(Zend_Search_Lucene_Index_Term $term, $docsFilter = null)
  1056. {
  1057. $result = array();
  1058. $segmentStartDocId = 0;
  1059. foreach ($this->_segmentInfos as $segmentInfo) {
  1060. $result += $segmentInfo->termPositions($term, $segmentStartDocId, $docsFilter);
  1061. $segmentStartDocId += $segmentInfo->count();
  1062. }
  1063. return $result;
  1064. }
  1065. /**
  1066. * Returns the number of documents in this index containing the $term.
  1067. *
  1068. * @param Zend_Search_Lucene_Index_Term $term
  1069. * @return integer
  1070. */
  1071. public function docFreq(Zend_Search_Lucene_Index_Term $term)
  1072. {
  1073. $result = 0;
  1074. foreach ($this->_segmentInfos as $segInfo) {
  1075. $termInfo = $segInfo->getTermInfo($term);
  1076. if ($termInfo !== null) {
  1077. $result += $termInfo->docFreq;
  1078. }
  1079. }
  1080. return $result;
  1081. }
  1082. /**
  1083. * Retrive similarity used by index reader
  1084. *
  1085. * @return Zend_Search_Lucene_Search_Similarity
  1086. */
  1087. public function getSimilarity()
  1088. {
  1089. /** Zend_Search_Lucene_Search_Similarity */
  1090. require_once 'Zend/Search/Lucene/Search/Similarity.php';
  1091. return Zend_Search_Lucene_Search_Similarity::getDefault();
  1092. }
  1093. /**
  1094. * Returns a normalization factor for "field, document" pair.
  1095. *
  1096. * @param integer $id
  1097. * @param string $fieldName
  1098. * @return float
  1099. */
  1100. public function norm($id, $fieldName)
  1101. {
  1102. if ($id >= $this->_docCount) {
  1103. return null;
  1104. }
  1105. $segmentStartId = 0;
  1106. foreach ($this->_segmentInfos as $segInfo) {
  1107. if ($segmentStartId + $segInfo->count() > $id) {
  1108. break;
  1109. }
  1110. $segmentStartId += $segInfo->count();
  1111. }
  1112. if ($segInfo->isDeleted($id - $segmentStartId)) {
  1113. return 0;
  1114. }
  1115. return $segInfo->norm($id - $segmentStartId, $fieldName);
  1116. }
  1117. /**
  1118. * Returns true if any documents have been deleted from this index.
  1119. *
  1120. * @return boolean
  1121. */
  1122. public function hasDeletions()
  1123. {
  1124. foreach ($this->_segmentInfos as $segmentInfo) {
  1125. if ($segmentInfo->hasDeletions()) {
  1126. return true;
  1127. }
  1128. }
  1129. return false;
  1130. }
  1131. /**
  1132. * Deletes a document from the index.
  1133. * $id is an internal document id
  1134. *
  1135. * @param integer|Zend_Search_Lucene_Search_QueryHit $id
  1136. * @throws Zend_Search_Lucene_Exception
  1137. */
  1138. public function delete($id)
  1139. {
  1140. if ($id instanceof Zend_Search_Lucene_Search_QueryHit) {
  1141. /* @var $id Zend_Search_Lucene_Search_QueryHit */
  1142. $id = $id->id;
  1143. }
  1144. if ($id >= $this->_docCount) {
  1145. require_once 'Zend/Search/Lucene/Exception.php';
  1146. throw new Zend_Search_Lucene_Exception('Document id is out of the range.');
  1147. }
  1148. $segmentStartId = 0;
  1149. foreach ($this->_segmentInfos as $segmentInfo) {
  1150. if ($segmentStartId + $segmentInfo->count() > $id) {
  1151. break;
  1152. }
  1153. $segmentStartId += $segmentInfo->count();
  1154. }
  1155. $segmentInfo->delete($id - $segmentStartId);
  1156. $this->_hasChanges = true;
  1157. }
  1158. /**
  1159. * Adds a document to this index.
  1160. *
  1161. * @param Zend_Search_Lucene_Document $document
  1162. */
  1163. public function addDocument(Zend_Search_Lucene_Document $document)
  1164. {
  1165. $this->_getIndexWriter()->addDocument($document);
  1166. $this->_docCount++;
  1167. $this->_hasChanges = true;
  1168. }
  1169. /**
  1170. * Update document counter
  1171. */
  1172. private function _updateDocCount()
  1173. {
  1174. $this->_docCount = 0;
  1175. foreach ($this->_segmentInfos as $segInfo) {
  1176. $this->_docCount += $segInfo->count();
  1177. }
  1178. }
  1179. /**
  1180. * Commit changes resulting from delete() or undeleteAll() operations.
  1181. *
  1182. * @todo undeleteAll processing.
  1183. */
  1184. public function commit()
  1185. {
  1186. if ($this->_hasChanges) {
  1187. $this->_getIndexWriter()->commit();
  1188. $this->_updateDocCount();
  1189. $this->_hasChanges = false;
  1190. }
  1191. }
  1192. /**
  1193. * Optimize index.
  1194. *
  1195. * Merges all segments into one
  1196. */
  1197. public function optimize()
  1198. {
  1199. // Commit changes if any changes have been made
  1200. $this->commit();
  1201. if (count($this->_segmentInfos) > 1 || $this->hasDeletions()) {
  1202. $this->_getIndexWriter()->optimize();
  1203. $this->_updateDocCount();
  1204. }
  1205. }
  1206. /**
  1207. * Returns an array of all terms in this index.
  1208. *
  1209. * @return array
  1210. */
  1211. public function terms()
  1212. {
  1213. $result = array();
  1214. /** Zend_Search_Lucene_Index_TermsPriorityQueue */
  1215. require_once 'Zend/Search/Lucene/Index/TermsPriorityQueue.php';
  1216. $segmentInfoQueue = new Zend_Search_Lucene_Index_TermsPriorityQueue();
  1217. foreach ($this->_segmentInfos as $segmentInfo) {
  1218. $segmentInfo->resetTermsStream();
  1219. // Skip "empty" segments
  1220. if ($segmentInfo->currentTerm() !== null) {
  1221. $segmentInfoQueue->put($segmentInfo);
  1222. }
  1223. }
  1224. while (($segmentInfo = $segmentInfoQueue->pop()) !== null) {
  1225. if ($segmentInfoQueue->top() === null ||
  1226. $segmentInfoQueue->top()->currentTerm()->key() !=
  1227. $segmentInfo->currentTerm()->key()) {
  1228. // We got new term
  1229. $result[] = $segmentInfo->currentTerm();
  1230. }
  1231. if ($segmentInfo->nextTerm() !== null) {
  1232. // Put segment back into the priority queue
  1233. $segmentInfoQueue->put($segmentInfo);
  1234. }
  1235. }
  1236. return $result;
  1237. }
  1238. /**
  1239. * Terms stream priority queue object
  1240. *
  1241. * @var Zend_Search_Lucene_TermStreamsPriorityQueue
  1242. */
  1243. private $_termsStream = null;
  1244. /**
  1245. * Reset terms stream.
  1246. */
  1247. public function resetTermsStream()
  1248. {
  1249. if ($this->_termsStream === null) {
  1250. /** Zend_Search_Lucene_TermStreamsPriorityQueue */
  1251. require_once 'Zend/Search/Lucene/TermStreamsPriorityQueue.php';
  1252. $this->_termsStream = new Zend_Search_Lucene_TermStreamsPriorityQueue($this->_segmentInfos);
  1253. } else {
  1254. $this->_termsStream->resetTermsStream();
  1255. }
  1256. }
  1257. /**
  1258. * Skip terms stream up to specified term preffix.
  1259. *
  1260. * Prefix contains fully specified field info and portion of searched term
  1261. *
  1262. * @param Zend_Search_Lucene_Index_Term $prefix
  1263. */
  1264. public function skipTo(Zend_Search_Lucene_Index_Term $prefix)
  1265. {
  1266. $this->_termsStream->skipTo($prefix);
  1267. }
  1268. /**
  1269. * Scans terms dictionary and returns next term
  1270. *
  1271. * @return Zend_Search_Lucene_Index_Term|null
  1272. */
  1273. public function nextTerm()
  1274. {
  1275. return $this->_termsStream->nextTerm();
  1276. }
  1277. /**
  1278. * Returns term in current position
  1279. *
  1280. * @return Zend_Search_Lucene_Index_Term|null
  1281. */
  1282. public function currentTerm()
  1283. {
  1284. return $this->_termsStream->currentTerm();
  1285. }
  1286. /**
  1287. * Close terms stream
  1288. *
  1289. * Should be used for resources clean up if stream is not read up to the end
  1290. */
  1291. public function closeTermsStream()
  1292. {
  1293. $this->_termsStream->closeTermsStream();
  1294. $this->_termsStream = null;
  1295. }
  1296. /*************************************************************************
  1297. @todo UNIMPLEMENTED
  1298. *************************************************************************/
  1299. /**
  1300. * Undeletes all documents currently marked as deleted in this index.
  1301. *
  1302. * @todo Implementation
  1303. */
  1304. public function undeleteAll()
  1305. {}
  1306. }