具體代碼如下:
//按term更新文檔(lucene並沒有提供專門的索引更新方法,我們需要先將相應的document刪除,然後再將新的document加入索引)
- public class MyUpdateIndexer{
- public static final String STORE_PATH = "E:/lucene_index";
- public static void updateIndexes(String field , String keyword) throws IOException{
- long startTime = System.currentTimeMillis();
- //首先,我們需要先將相應的document刪除
- Directory dir = FSDirectory.open(new File(STORE_PATH));
- IndexReader reader = IndexReader.open(dir,false);
- Term term = new Term(field,keyword);
- reader.deleteDocuments(term);
- reader.close();
- //然後,將新的document加入索引
- Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
- //CREATE - creates a new index or overwrites an existing one
- //APPEND - opens an existing index.
- //CREATE_OR_APPEND - creates a new index if one does not exist,otherwise it opens the index and documents will be appended.
- IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35,analyzer).setOpenMode(OpenMode.CREATE);
- IndexWriter writer = new IndexWriter(dir, config);
- for(int i = 0;i<100;i++){
- Document doc = new Document();
- doc.add(new Field("title", "lucene title"+i, Field.Store.YES, Field.Index.ANALYZED));
- doc.add(new Field("content", "Apache Lucene(TM) is a high-performance", Field.Store.YES, Field.Index.ANALYZED));
- //純文本文件索引起來,而不想自己將它們讀入字符串創建field
- //這裏的file就是該文本文件。該構造函數實際上是讀去文件內容,並對其進行索引,但不存儲。
- //doc.add(new Field("path", new FileReader(new File("路徑"))));
- writer.addDocument(doc);
- }
- }
- writer.close();
- long endTime = System.currentTimeMillis();
- System.out.println("total time: " + (endTime - startTime) + " ms");
- }
- }