Lucene的索引庫的維護分為四個部分,增刪改查,這里就先只講增刪改,查會在下一篇文章單獨拎出來講。
1.添加文檔
2.刪除文檔
1) 刪除全部
2) 根據(jù)查詢、關鍵詞刪除文檔
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 {
//創(chuàng)建一個IndexWriter對象,需要使用IKAnalyzer作為分析器
indexWriter=
new IndexWriter(FSDirectory.open(new File("E:\\Desktop").toPath()),
new IndexWriterConfig(new IKAnalyzer()));
}
@Test
public void addDocument() throws ParseException, IOException {
//創(chuàng)建一個Document對象
Document document=new Document();
//向document對象中添加域
document.add(new TextField("name","新添加的文件", Field.Store.YES));
document.add(new TextField("context","新添加的文件內(nèi)容", 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 {
//創(chuàng)建一個新的文檔對象
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();
}
}