lucene索引库的维护
维护的方式
这里我们要先解释两个名词:分词与索引
分词:分词指的是我们索引库中所存储的关键字,通过索引我们可以从关键字找的文档中对应的内容;
索引:指的是分词(也就是关键字)与文档内容的关联,我们可以将分词和文档看成两个组,而索引就相当于是两个组之间的连线;
注意:我们对索引库进行维护时,并不会真正的对分词或者文档进行操作,而是对索引(也就是两者之间的关联)进行操作。
增删与更新的代码:
package cn.itcast.lucene;/*** 感谢詹姆斯.高斯林!* 有志者,事竟成!* 少壮不努力,老大徒伤悲!*/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.store.FSDirectory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;import java.io.File;
import java.io.IOException;/*** 测试全文检索索引库维护(增删更新)*/
public class IndexManager {private IndexWriter indexWriter;/*** 初始化资源的方法*/@Beforepublic void init() throws IOException {indexWriter = new IndexWriter(FSDirectory.open(new File("E:\\index").toPath()),new IndexWriterConfig(new IKAnalyzer()));}/*** 释放资源的方法*/@Afterpublic void destroy() throws IOException {indexWriter.close();}/*** 测试增加*/@Testpublic void addDocument() throws IOException {// 1.创建Document对象Document document = new Document();// 2.向Document中添加域document.add(new TextField("name","新添加的文件", Field.Store.YES));document.add(new TextField("content","新添加的文件内容", Field.Store.NO));document.add(new StoredField("path","新添加的文件"));// 3.写入indexWriter.addDocument(document);}/*** 测试删除全部文档*/@Testpublic void deleteAll() throws IOException {indexWriter.deleteAll();}/*** 根据Query删除索引*/@Testpublic void deleteDocumentByQuery() throws IOException {indexWriter.deleteDocuments(new Term("name","apache"));}/*** 更新*/@Testpublic void updateDocument() throws IOException {//创建一个新的文档对象Document document = new Document();//向文档对象中添加域document.add(new TextField("name", "更新", Field.Store.YES));//更新操作indexWriter.updateDocument(new Term("name", "spring"), document);}
}
值得注意的是,在执行更新操作时,我们会将索引库中废弃的索引删除,再加入新的索引,但是旧的索引与新的索引之间并不一定有什么关系,我们只是废弃了一个旧的,加入了一个新的,仅此而已。
新人入驻,希望得到您的鼓励和支持,谢谢!