搜索引擎学习(五)Lucene操作索引
生活随笔
收集整理的這篇文章主要介紹了
搜索引擎学习(五)Lucene操作索引
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、代碼分析
/*** Lucene入門* 操作索引*/ public class ManageIndex {public IndexWriter getIndexWriter() throws Exception {//設置索引庫的位置Directory directory = FSDirectory.open(new File("E:\\zhanghaoBF\\luceneSolr\\indexLibrary").toPath());Analyzer analyzer = new StandardAnalyzer();//創建分詞器對象(官方推薦標準分詞器)IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);//設置使用的分詞器return new IndexWriter(directory, indexWriterConfig);//索引對象 }/*** 全刪除(PS:索引里面的文檔也會刪掉)** @throws Exception*/@Testpublic void deleteAllIndex() throws Exception {IndexWriter indexWriter = getIndexWriter();//獲取索引的流對象indexWriter.deleteAll();//刪除全部索引indexWriter.close();//關流 }/*** 按條件刪除(PS:索引里面的文檔也會刪掉)** @throws Exception*/@Testpublic void deleteIndex() throws Exception {IndexWriter indexWriter = getIndexWriter();//獲取索引的流對象Query query = new TermQuery(new Term("fileContent", "lucene"));//PS:TermQuery為精準匹配indexWriter.deleteDocuments(query);//按條件刪除索引indexWriter.close();//關流 }/*** 修改(PS:先刪除后新增,與數據庫里面的修改不一樣,注意區分)** @throws Exception*/@Testpublic void updateIndex() throws Exception {//獲取索引的流對象IndexWriter indexWriter = getIndexWriter();//構建一個文檔對象Document doc = new Document();doc.add(new TextField("fileName", "新的文件名稱", Field.Store.YES));doc.add(new TextField("fileContent", "新的文件內容", Field.Store.YES));//調用更新操作,先把符合條件的索引刪掉(包括term和存在索引庫的文檔),然后把剛才新增的文檔對象加入到索引庫中indexWriter.updateDocument(new Term("fileName", "是"), doc);//按條件刪除索引,再加入新的索引//PS:刪掉的文檔還是會占用對應的文檔ID,新增的文檔排在最后(和數據庫ID自增時的刪除再添加一個道理)//關流 indexWriter.close();} }二、注意事項
1、刪除的時候,索引庫里對應ID下的term和文檔都會刪除。
2、修改操作其實是先把符合條件的term和文檔都會刪掉,然后再加入新的文檔。
3、刪掉的文檔,文檔ID不會釋放,還是被占用的。
4、流用完一定要記得關。
轉載于:https://www.cnblogs.com/riches/p/11450606.html
總結
以上是生活随笔為你收集整理的搜索引擎学习(五)Lucene操作索引的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 搜索引擎学习(三)Lucene查询索引
- 下一篇: 搜索引擎学习(四)中文分词器