Lucene.php 46 KB

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