標籤:
- 一,Lucene建索引API
- 二,建立IndexWriter
- 三,建立Document
- 四,添加Document
- 1 Lucene使用情境
- 2 重要的幾個基礎類
- 2.1 DocumentsWriterPerThreadPool
- 2.2 ThreadState
- 2.3 DocumentsWriterPerThread
- 2.4 DocumentsWriterFlushControl
- 2.5 FlushPolicy
- 3 docWriter.updateDocument
- 4 docWriter.updateDocument詳細步驟
- 5 DocumentsWriterPerThread.updateDocument詳細步驟
- 6 DefaultIndexingChain.processDocument詳細步驟
- 五,Commit Document
- 六,關閉IndexWriter
本文檔旨在分析Lucene如何把商務資訊寫到磁碟上的大致流程,並不涉及Document中每個Field如何儲存(該部分放在另外一篇wiki中介紹)。
一,Lucene建索引API
Directory dire = NIOFSDirectory.open(FileSystems.getDefault().getPath(indexDirectory));IndexWriterConfig iwc = new IndexWriterConfig(new StandardAnalyzer());iwc.setRAMBufferSizeMB(64); //兆預設刷indexWriter = new IndexWriter(dire, iwc); Document doc = createDocument(artiste, skuId);indexWriter.addDocument(doc); indexWriter.commit();indexWriter.close();
二,建立IndexWriter
如果是64位JRE會得到MMapDirectory(採用記憶體映射的方式寫索引資料到File中)。
IndexWriterConfig //propertiesthis.analyzer = analyzer;ramBufferSizeMB = IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB;//預設超過16M就會觸發flush磁碟操作maxBufferedDocs = IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS;//預設按照RAM空間大小觸發flushmaxBufferedDeleteTerms = IndexWriterConfig.DEFAULT_MAX_BUFFERED_DELETE_TERMS;//mergedSegmentWarmer = null;delPolicy = new KeepOnlyLastCommitDeletionPolicy();//刪除策略commit = null;useCompoundFile = IndexWriterConfig.DEFAULT_USE_COMPOUND_FILE_SYSTEM;openMode = OpenMode.CREATE_OR_APPEND;//IndexWriter開啟模式similarity = IndexSearcher.getDefaultSimilarity();//相似性計算,一般初始化Searcher的時候會用(因為只有查詢的時候才會用到相似性計算)mergeScheduler = new ConcurrentMergeScheduler();//每個segement的merge交個一個線程完成writeLockTimeout = IndexWriterConfig.WRITE_LOCK_TIMEOUT;//寫操作遇到鎖逾時時間indexingChain = DocumentsWriterPerThread.defaultIndexingChain;codec = Codec.getDefault();if (codec == null) { throw new NullPointerException();}infoStream = InfoStream.getDefault();mergePolicy = new TieredMergePolicy();//合并策略flushPolicy = new FlushByRamOrCountsPolicy();//flush策略readerPooling = IndexWriterConfig.DEFAULT_READER_POOLING;indexerThreadPool = new DocumentsWriterPerThreadPool(IndexWriterConfig.DEFAULT_MAX_THREAD_STATES);//並發寫索引線程池perThreadHardLimitMB = IndexWriterConfig.DEFAULT_RAM_PER_THREAD_HARD_LIMIT_MB;
可以對IndexWriter做一些屬性配置,IndexWriterConfig裡面有非常豐富的各種配置。
三,建立Document
這個步驟比較簡單,主要是將業務欄位組裝成一個Document。一個Document由多個Field組成的。
每個Filed一般有四個屬性群組成:
- name:該欄位的名稱
- value:該欄位的值
- value是否需要儲存到索引檔案中:如果儲存到索引檔案中,則search的時候可以從Document中讀取到該欄位的值
- value值是否被索引:如果該欄位被索引,則可以通過該欄位為條件進行檢索
四,添加Document
添加一個Document,其實調用的是updateDocument。而Lucene更新Document不像Mysql可以直接更新某一條記錄,所以只能先刪除這條記錄(Document),然後再添加上這條Document。下面參數Term,是一個檢索條件,滿足條件的Document做更新。
public void updateDocument(Term term, Iterable<? extends IndexableField> doc) throws IOException { ensureOpen(); try { boolean success = false; try { if (docWriter.updateDocument(doc, analyzer, term)) { processEvents(true, false); } success = true; } finally { if (!success) { if (infoStream.isEnabled("IW")) { infoStream.message("IW", "hit exception updating document"); } } } } catch (AbortingException | OutOfMemoryError tragedy) { tragicEvent(tragedy, "updateDocument"); }}1 Lucene使用情境
這裡從下面幾個角度闡述下為什麼Lucene不能直接更新一個Document?
- Lucene的設計本質是一個面向檢索,或者面向讀的系統。為了方面的檢索,在建立索引的時候做了大量的讀取最佳化儲存設計。簡而言之,為了讀的效能,犧牲了方便寫、更新的操作。
- Lucene使用背景暗含了:Lucene適合(擅長)頻繁讀,不常寫的情境。
所以上面添加一個Document,最後演變成了更新一個Document。並且updateDocument包含兩個串列操作
(1)先檢索,如果有滿足條件的Document,則刪除
(2)如果沒有滿足條件的Document,則直接添加到記憶體中
2 重要的幾個基礎類
在看docWriter.updateDocument(doc, analyzer, term)代碼之前,我們先看幾個Lucene子建的類,下面著重分析下:
2.1 DocumentsWriterPerThreadPool
Lucene內部實現的一個DocumentsWriterPerThread池(並不是嚴格意義的線程池),主要是
實現DocumentsWriterPerThread的重用(準確來說是實現ThreadState的重用)。該類可以簡單理解一個線程池。
2.2 ThreadState
/*{@link ThreadState} references and guards a* {@link DocumentsWriterPerThread} instance that is used during indexing to build a in-memory index segment.*/final static class ThreadState extends ReentrantLock { DocumentsWriterPerThread dwpt; // TODO this should really be part of DocumentsWriterFlushControl // write access guarded by DocumentsWriterFlushControl volatile boolean flushPending = false; // TODO this should really be part of DocumentsWriterFlushControl // write access guarded by DocumentsWriterFlushControl long bytesUsed = 0; // guarded by Reentrant lock private boolean isActive = true; ThreadState(DocumentsWriterPerThread dpwt) { this.dwpt = dpwt; }
本質是個讀寫鎖,用來配合DocumentsWriterPerThread來完成對一個Document的寫操作。
2.3 DocumentsWriterPerThread
簡單理解成一個Document的寫線程。線程池保證了DocumentsWriterPerThread的重用。
2.4 DocumentsWriterFlushControl
控制DocumentsWriterPerThread完成index過程中flush操作
2.5 FlushPolicy
重新整理策略
理解了ThreadState這個類應該就簡單了,甚至可以直接把該類看做帶讀寫鎖控制的寫線程。其實是ThreadState內部引用DocumentWriterPerThread執行個體。線上程池初始化的時候就建立了8個ThreadState(這個時候並沒有初始化,意思是DocumentWriterPerThread並沒有建立起來,而是延遲初始化具體線程)。後面就盡量重用這個8個ThreadState。
DocumentsWriterPerThreadPool(int maxNumThreadStates) {//預設maxNumThreadStates=8 if (maxNumThreadStates < 1) { throw new IllegalArgumentException("maxNumThreadStates must be >= 1 but was: " + maxNumThreadStates); } threadStates = new ThreadState[maxNumThreadStates]; numThreadStatesActive = 0; for (int i = 0; i < threadStates.length; i++) { threadStates[i] = new ThreadState(null); } freeList = new ThreadState[maxNumThreadStates];}3 docWriter.updateDocument
好了,看完了幾個基礎類,回到上面updateDocument最關鍵的是這一行。
docWriter.updateDocument(doc, analyzer, term) boolean updateDocument(final Iterable<? extends IndexableField> doc, final Analyzer analyzer, final Term delTerm) throws IOException, AbortingException { boolean hasEvents = preUpdate(); final ThreadState perThread = flushControl.obtainAndLock(); final DocumentsWriterPerThread flushingDWPT; try { if (!perThread.isActive()) { ensureOpen(); assert false: "perThread is not active but we are still open"; } ensureInitialized(perThread);//真正初始化單個具體線程DocumentsWriterPerThread assert perThread.isInitialized(); final DocumentsWriterPerThread dwpt = perThread.dwpt; final int dwptNumDocs = dwpt.getNumDocsInRAM(); try { dwpt.updateDocument(doc, analyzer, delTerm); //DocumentsWriterPerThread線程真正更新文檔 } catch (AbortingException ae) { flushControl.doOnAbort(perThread); dwpt.abort(); throw ae; } finally { // We don‘t know whether the document actually // counted as being indexed, so we must subtract here to // accumulate our separate counter: numDocsInRAM.addAndGet(dwpt.getNumDocsInRAM() - dwptNumDocs); } final boolean isUpdate = delTerm != null; flushingDWPT = flushControl.doAfterDocument(perThread, isUpdate); } finally { perThreadPool.release(perThread);//將該線程重新放回到線程池中,釋放掉資源 } return postUpdate(flushingDWPT, hasEvents);} 4 docWriter.updateDocument詳細步驟
-
從線程池中擷取一個ThreadState
ThreadState obtainAndLock() { final ThreadState perThread = perThreadPool.getAndLock(Thread .currentThread(), documentsWriter);//從線程池中拿取一個ThreadState boolean success = false; try { if (perThread.isInitialized() && perThread.dwpt.deleteQueue != documentsWriter.deleteQueue) { // There is a flush-all in process and this DWPT is // now stale -- enroll it for flush and try for // another DWPT: addFlushableState(perThread); } success = true; // simply return the ThreadState even in a flush all case sine we already hold the lock return perThread; } finally { if (!success) { // make sure we unlock if this fails perThreadPool.release(perThread); } }}
- 初始化ThreadState的線程DocumentsWriterPerThread
- 該線程更新Document
- 該線程重新回到線程池中。線程池中維護了一個freeList,可重用的ThreadState都放到該freeList裡面
5 DocumentsWriterPerThread.updateDocument詳細步驟
該Document的更新交給一個DocumentsWriterPerThread之後,我們再往下看。
public void updateDocument(Iterable<? extends IndexableField> doc, Analyzer analyzer, Term delTerm) throws IOException, AbortingException { testPoint("DocumentsWriterPerThread addDocument start"); assert deleteQueue != null; reserveOneDoc(); docState.doc = doc; docState.analyzer = analyzer; docState.docID = numDocsInRAM; if (INFO_VERBOSE && infoStream.isEnabled("DWPT")) { infoStream.message("DWPT", Thread.currentThread().getName() + " update delTerm=" + delTerm + " docID=" + docState.docID + " seg=" + segmentInfo.name); } // Even on exception, the document is still added (but marked // deleted), so we don‘t need to un-reserve at that point. // Aborting exceptions will actually "lose" more than one // document, so the counter will be "wrong" in that case, but // it‘s very hard to fix (we can‘t easily distinguish aborting // vs non-aborting exceptions): boolean success = false; try { try { consumer.processDocument(); } finally { docState.clear(); } success = true; } finally { if (!success) { // mark document as deleted deleteDocID(docState.docID); numDocsInRAM++; } } finishDocument(delTerm);}
該線程裡面我們只關心一行代碼
consumer.processDocument(); |
從這裡差不多就豁然開朗了,一切最後該Document的處理是交給了一個DocConsumer來處理。而這個DocConsumer的擷取見下:
abstract DocConsumer getChain(DocumentsWriterPerThread documentsWriterPerThread) throws IOException; |
Lucene實現了一個預設的DocConsumer即:DefaultIndexingChain。 那接下來就看該DocConsumer是如何處理該Document的了就行了。
6 DefaultIndexingChain.processDocument詳細步驟
@Overridepublic void processDocument() throws IOException, AbortingException { // How many indexed field names we‘ve seen (collapses // multiple field instances by the same name): int fieldCount = 0; long fieldGen = nextFieldGen++; // NOTE: we need two passes here, in case there are // multi-valued fields, because we must process all // instances of a given field at once, since the // analyzer is free to reuse TokenStream across fields // (i.e., we cannot have more than one TokenStream // running "at once"): termsHash.startDocument(); fillStoredFields(docState.docID); startStoredFields(); boolean aborting = false; try { for (IndexableField field : docState.doc) {//挨個遍曆每個Field做處理,哈哈,終於露出可愛的尾巴了 fieldCount = processField(field, fieldGen, fieldCount); } } catch (AbortingException ae) { aborting = true; throw ae; } finally { if (aborting == false) { // Finish each indexed field name seen in the document: for (int i=0;i<fieldCount;i++) { fields[i].finish(); } finishStoredFields(); } } try { termsHash.finishDocument(); } catch (Throwable th) { // Must abort, on the possibility that on-disk term // vectors are now corrupt: throw AbortingException.wrap(th); }}
看到上面代碼,我笑了。哈哈,越來越清晰,有沒有。對該Document的處理,無非就是演化成遍曆每個Field,對Field做處理就行了。但是具體Field怎麼處理,該wiki不涉及,放到另外一篇wiki中深入記錄(參考:Document儲存細節)。
五,Commit Document
提交Commit完成如下工作:
- 凡是掛起的改變都提交到index中。包括新增加的文檔,要刪除的文檔,segement的合并。
- 該操作會執行Directory.sync,sync操作會將檔案系統的cache都重新整理到disk上面。雖然比較耗時(同步耗時),但是重新整理到disk上之後,VM掛掉(或者斷電)都不影響這些掛起的更新。
sync操作具體的解釋可參考如下一段解釋:
傳統的UNIX實現在核心中設有緩衝區快取或頁面快取,大多數磁碟I/O都通過緩衝進行。當將資料寫入檔案時,核心通常先將該資料複製到其中一個緩衝區中,如果該緩衝區尚未寫滿,則並不將其排入輸出隊列,而是等待其寫滿或者當核心需要重用該緩衝區以便存放其他磁碟塊資料時,再將該緩衝排入輸出隊列,然後待其到達隊首時,才進行實際的I/O操作。這種輸出方式被稱為延遲寫(delayed write)(Bach [1986]第3章詳細討論了緩衝區快取)。延遲寫減少了磁碟讀寫次數,但是卻降低了檔案內容的更新速度,使得欲寫到檔案中的資料在一段時間內並沒有寫到磁碟上。當系統發生故障時,這種延遲可能造成檔案更新內容的丟失。為了保證磁碟上實際檔案系統與緩衝區快取中內容的一致性,UNIX系統提供了sync、fsync和fdatasync三個函數。sync函數只是將所有修改過的塊緩衝區排入寫隊列,然後就返回,它並不等待實際寫磁碟操作結束。通常稱為update的系統守護進程會周期性地(一般每隔30秒)調用sync函數。這就保證了定期沖洗核心的塊緩衝區。命令sync(1)也調用sync函數。fsync函數只對由檔案描述符filedes指定的單一檔案起作用,並且等待寫磁碟操作結束,然後返回。fsync可用於資料庫這樣的應用程式,這種應用程式需要確保將修改過的塊立即寫到磁碟上。fdatasync函數類似於fsync,但它隻影響檔案的資料部分。而除資料外,fsync還會同步更新檔案的屬性。對於提供事務支援的資料庫,在事務提交時,都要確保交易記錄(包含該事務所有的修改操作以及一個提交記錄)完全寫到硬碟上,才認定事務提交成功並返回給應用程式層。
看完這段解釋就能明白,sync操作就是將檔案系統(甚至核心)中的快取資料都重新整理到disk上面,保證資料的安全性(OS掛掉,斷電,資料不會丟失)。
那具體Lucene做了些什麼呢?
private final void commitInternal(MergePolicy mergePolicy) throws IOException { if (infoStream.isEnabled("IW")) { infoStream.message("IW", "commit: start"); } synchronized(commitLock) { ensureOpen(false); if (infoStream.isEnabled("IW")) { infoStream.message("IW", "commit: enter lock"); } if (pendingCommit == null) { if (infoStream.isEnabled("IW")) { infoStream.message("IW", "commit: now prepare"); } prepareCommitInternal(mergePolicy);//最關鍵的一行 } else { if (infoStream.isEnabled("IW")) { infoStream.message("IW", "commit: already prepared"); } } finishCommit(); }}
走到prepareCommitInternal裡面就是詳細的重新整理操作,索引重新整理操作放在另外一篇wiki中介紹。
六,關閉IndexWriter
重新整理資料,關閉資源。往裡走,邏輯還是很豐富的。等flush詳細講完之後,再回頭看這部分。
Lucene索引建立過程