lucene3.5更新索引

lucene索引的更新操作其实就是删除索引和添加索引的组合。
具体代码如下:
//按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");
	}
}

你可能感兴趣的:(document,Lucene,store,updateindexes)