Lucene的索引库的维护分为四个部分,增删改查,这里就先只讲增删改,查会在下一篇文章单独拎出来讲。
1.添加文档
2.删除文档
1) 删除全部
2) 根据查询、关键词删除文档
3.修改文档
修改的原理时先删除后添加
代码如下:
package com.itheima;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.store.FSDirectory;
import org.junit.Before;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;
import java.io.File;
import java.io.IOException;
/**
* @ClassName luceneFive
* @Description TODO
* @Author gkz
* @Date 2019/8/23 16:59
* @Version 1.0
**/
public class luceneFive {
private IndexWriter indexWriter;
@Before()
public void initIndexWriter() throws IOException {
//创建一个IndexWriter对象,需要使用IKAnalyzer作为分析器
indexWriter=
new IndexWriter(FSDirectory.open(new File("E:\\Desktop").toPath()),
new IndexWriterConfig(new IKAnalyzer()));
}
@Test
public void addDocument() throws ParseException, IOException {
//创建一个Document对象
Document document=new Document();
//向document对象中添加域
document.add(new TextField("name","新添加的文件", Field.Store.YES));
document.add(new TextField("context","新添加的文件内容", Field.Store.NO));
document.add(new StoredField("path","E:\\Desktop\\lucenetest"));
//把文档对象写入索引库
indexWriter.addDocument(document);
//关闭索引库
indexWriter.close();
}
@Test
public void deleteAllDocument() throws IOException {
//删除所有文档
indexWriter.deleteAll();
indexWriter.close();
}
@Test
public void deleteDocumentByQuery() throws IOException {
//删除name域带apache的所有的文档
indexWriter.deleteDocuments(new Term("name","apache"));
indexWriter.close();
}
@Test
public void updateDocument() throws IOException {
//创建一个新的文档对象
Document document=new Document();
document.add(new TextField("name","更新之后的文档", Field.Store.YES));
document.add(new TextField("name1","更新之后的文档2", Field.Store.YES));
document.add(new TextField("name2","更新之后的文档3", Field.Store.YES));
indexWriter.updateDocument(new Term("name2","spring"),document);
//关闭索引库
indexWriter.close();
}
}