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