一步一步跟我學習lucene(5)---lucene的索引構建原理

lucene創建索引的原理

IndexWriter的addDocument方法詳解

今天看了IndexWriter類的addDocument方法,IndexWriter對此方法的說明如下:

Adds a document to this index. 

Note that if an Exception is hit (for example disk full) then the index will be consistent, but this document may not have been added. Furthermore, it's possible the index will have one segment in non-compound format even when using compound files (when a merge has partially succeeded).

This method periodically flushes pending documents to the Directory (see above), and also periodically triggers segment merges in the index according to the MergePolicy in use.

Merges temporarily consume space in the directory. The amount of space required is up to 1X the size of all segments being merged, when no readers/searchers are open against the index, and up to 2X the size of all segments being merged when readers/searchers are open against the index (see forceMerge(int) for details). The sequence of primitive merge operations performed is governed by the merge policy. 

Note that each term in the document can be no longer than MAX_TERM_LENGTH in bytes, otherwise an IllegalArgumentException will be thrown.

大意如下:

此方法向索引中添加一個document;

需要注意的是如果執行過程中發生異常(比如磁盤空間不足)的時候索引會保持一致性,但是這個document也許並沒有被添加,此外,即使使用符合文件也有可能索引包含一個非複合格式的segment當合並索引有部分成功的時候)

此方法會定期的flush索引文件目錄,並且會根據合併策略定期去觸發索引文件中segment的合併操作;

剛方法會對合並臨時的索引空間,當沒有reader或者searcher讀取或寫入索引文件的時候所需要佔用的磁盤空間至少要超過需要合併的segments文件的一倍,反之將會佔用兩倍以上的空間;序列的合併操作的優化取決於合併策略‘

要確保document中的每一個term佔用的字節長度都不能超過MAX_TERM_LENGTH,否則會拋出IllegalArgumentException異常;

其實際的執行方法爲:

繼續跟進updateDocument方法,其實現如下

可以看見updateDocument是先從索引中刪除包含相同term的document然後重新添加document到索引中;

此操作需要確保IndexWriter沒有被關閉,其實現是先有DocumentsWriter類的updateDocument方法判斷,這裏先判斷將根據term找到對應的document,並先放到待刪除的document隊列中,然後從隊列中讀取document,再將要flush的documents寫入磁盤,同時更新flush隊列中的索引狀態;

相關源碼如下


在此期間有一個ThreadState類型的讀寫鎖,lucene判斷ThreadState的狀態,如果此鎖被激活,從內存中獲取document並更新到索引文件且重置內存中索引的數量和狀態,最後釋放相關的資源。

此即爲IndexWriter的索引構建過程,看代碼暈頭轉向的,以後爲大家帶來一點乾貨,明天帶來lucene索引優化之多線程創建索引。

聯繫我

一步一步跟我學習lucene是對近期做lucene索引的總結,大家有問題的話聯繫本人的Q-Q:  891922381,同時本人新建Q-Q羣:106570134(lucene,solr,netty,hadoop),如蒙加入,不勝感激,大家共同探討,本人爭取每日一博,希望大家持續關注,會帶給大家驚喜的




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章