lucene3.5更新索引

lucene索引的更新操作其實就是刪除索引和添加索引的組合。 
具體代碼如下: 
//按term更新文檔(lucene並沒有提供專門的索引更新方法,我們需要先將相應的document刪除,然後再將新的document加入索引) 
Java代碼  收藏代碼
  1. public class MyUpdateIndexer{  
  2.     public static final String STORE_PATH = "E:/lucene_index";  
  3.     public static void updateIndexes(String field , String keyword) throws IOException{  
  4.         long startTime = System.currentTimeMillis();  
  5.         //首先,我們需要先將相應的document刪除  
  6.         Directory dir = FSDirectory.open(new File(STORE_PATH));  
  7.         IndexReader reader = IndexReader.open(dir,false);  
  8.         Term term = new Term(field,keyword);  
  9.         reader.deleteDocuments(term);  
  10.         reader.close();  
  11.         //然後,將新的document加入索引  
  12.         Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);  
  13.         //CREATE - creates a new index or overwrites an existing one  
  14.         //APPEND - opens an existing index.  
  15.         //CREATE_OR_APPEND - creates a new index if one does not exist,otherwise it opens the index and documents will be appended.  
  16.         IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35,analyzer).setOpenMode(OpenMode.CREATE);  
  17.         IndexWriter writer = new IndexWriter(dir, config);  
  18.         for(int i = 0;i<100;i++){  
  19.             Document doc = new Document();   
  20.             doc.add(new Field("title""lucene title"+i, Field.Store.YES, Field.Index.ANALYZED));   
  21.             doc.add(new Field("content""Apache Lucene(TM) is a high-performance", Field.Store.YES, Field.Index.ANALYZED));  
  22.             //純文本文件索引起來,而不想自己將它們讀入字符串創建field  
  23.             //這裏的file就是該文本文件。該構造函數實際上是讀去文件內容,並對其進行索引,但不存儲。  
  24.             //doc.add(new Field("path", new FileReader(new File("路徑"))));  
  25.             writer.addDocument(doc);  
  26.         }  
  27. }  
  28.         writer.close();  
  29.         long endTime = System.currentTimeMillis();  
  30.         System.out.println("total time: " + (endTime - startTime) + " ms");  
  31.     }  
  32. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章