Lucene对索引库的管理维护:
添加文档对象、删除文档对象、修改文档对象
package cn.lxh.lucene;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
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.search.TermQuery;
import org.apache.lucene.store.FSDirectory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;
import java.io.File;
/**
* 对索引库的维护管理操作(CRUD)
*/
public class IndexManager {
private IndexWriter indexWriter;
/**
* 初始化IndexWriter对象
* @throws Exception
*/
@Before
public void init() throws Exception{
//创建一个IndexWriter对象,需要使用IKAnalyzer作为分析器
indexWriter = new IndexWriter(FSDirectory.open(new File("F:\\IndexLibrery").toPath()),
new IndexWriterConfig(new IKAnalyzer()));
}
/**
* 执行方法后,销毁,关闭索引库
* @throws Exception
*/
@After
public void destory() throws Exception{
//关闭索引库
indexWriter.close();
}
/**
* 向索引库中添加文档对象
*/
@Test
public void addDocument() throws Exception{
//创建document对象
Document document = new Document();
//向文本域中添加域对象
document.add(new TextField("name","新添加的文本", Field.Store.YES));
document.add(new TextField("content","新添加的文本内容", Field.Store.NO));
document.add(new TextField("path","F:\\index", Field.Store.YES));
//把文档写入索引库
indexWriter.addDocument(document);
}
/**
* 删除所有的文本对象
* @throws Exception
*/
@Test
public void deleteAllDocument() throws Exception{
//删除所有的文本对象
indexWriter.deleteAll();
}
/**
* 删除指定的文本对象
*/
@Test
public void deleteDocument() throws Exception{
//删除指定的文本对象,删除name域中含有“apache”的文档对象
//方式一:使用Term
indexWriter.deleteDocuments(new Term("name,","apache"));
//方式二:使用TermQuery
indexWriter.deleteDocuments(new TermQuery(new Term("name,","apache")));
}
/**
* 修改指定的文档对象
* 原理:
* 先删除指定的索引,然后再添加相同名称的索引
*/
@Test
public void updateDocument() throws Exception{
//创建文档对象
Document document = new Document();
document.add(new TextField("name","更新后的文本", Field.Store.YES));
document.add(new TextField("name2","更新后的文本2", Field.Store.YES));
//修改name域中含有“spring”的文档对象
indexWriter.updateDocument(new Term("name","spring"),document);
}
}