lucene索引的删除和更新
生活随笔
收集整理的這篇文章主要介紹了
lucene索引的删除和更新
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Lucene索引的刪除和更新
刪除和更新和新增一樣,也是通過IndexWriter 對象來操作的,IndexWrite對象的deleteDocuments ()方法用于實現索引的刪除,updateDocument()方法用于實現索引的更新。
刪除Lucene索引
刪除索引的代碼如下,該示例實現了根據Term來刪除單個或多個Document,刪除title中包含關鍵詞“美國”的文檔:
import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.Term; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import tup.lucene.ik.IKAnalyzer6x; public class DeleteIndex {public static void main(String[] args) {// 刪除title中含有關鍵詞“美國”的文檔deleteDoc("title", "美國"); } public static void deleteDoc(String field, String key) {Analyzer analyzer = new IKAnalyzer6x();IndexWriterConfig icw = new IndexWriterConfig(analyzer);Path indexPath = Paths.get("indexdir");Directory directory;try {directory = FSDirectory.open(indexPath);IndexWriter indexWriter = new IndexWriter(directory, icw);indexWriter.deleteDocuments(new Term(field, key));indexWriter.commit();indexWriter.close();System.out.println("刪除完成!");} catch (IOException e) {e.printStackTrace();} } }除此之外IndexWriter還提供了以下方法:
- DeleteDocuments(Query query):根據Query條件來刪除單個或多個Document
- DeleteDocuments(Query[] queries):根據Query條件來刪除單個或多個Document
- DeleteDocuments(Term term):根據Term來刪除單個或多個Document
- DeleteDocuments(Term[] terms):根據Term來刪除單個或多個Document
- DeleteAll():刪除所有的Document
更新Lucene索引
使用IndexWriter進行Document刪除操作時,文檔并不會立即被刪除,而是把這個刪除動作緩存起來,當IndexWriter.Commit()或IndexWriter.Close()時,刪除操作才會被真正執行。
索引更新操作實質上是先刪除索引,再重新建立新的文檔,示例代碼如下:
上面的代碼中我們新建了一個IndexWriter對象和Document對象,通過updateDocument()方法完成更新操作。Term對象用于定位文檔,查找title中含有“北大”的文檔,然后用新的文檔替換原文檔,這樣就完成了索引的更新操作。
總結
以上是生活随笔為你收集整理的lucene索引的删除和更新的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript设计模式之发布-订阅
- 下一篇: 浅析call和apply的不同