lucene索引的增、删、改

package com.hope.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.Before;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;

/**
* @author newcityman
* @date 2020/1/15 - 17:22
*/
public class IndexManager {
private IndexWriter indexWriter;

@Before
public void init() throws Exception {
//创建一个IndexWriter对象,需要使用IKAnalyzer作为分词器
indexWriter = new IndexWriter(FSDirectory.open(new File("G:\\workspace_idea3\\lucene\\temp\\index").toPath()),
new IndexWriterConfig(new IKAnalyzer()));
}

/**
* 添加索引
* @throws Exception
*/
@Test
public void addDocument() throws Exception {

//创建一个Document对象
Document document = new Document();
//向Document对象中添加Field域
document.add(new TextField("name", "新添加的文件", Field.Store.YES));
document.add(new TextField("content", "新添加的文件内容", Field.Store.NO));
document.add(new StoredField("path", "G:\\workspace_idea3\\lucene\\temp\\index"));
//把文档写入索引库
indexWriter.addDocument(document);
//关闭索引库
indexWriter.close();
}

/**
* 删除索引
* @throws Exception
*/
@Test
public void deleteAllDocument() throws Exception {
//删除所有文档
indexWriter.deleteAll();
//关闭索引库
indexWriter.close();
}

/**
* 根据条件删除索引
*/
@Test
public void deleteDocumentByQuery() throws Exception{
indexWriter.deleteDocuments(new Term("content","apache"));
indexWriter.close();
}

/**
* 修改索引
*/
@Test
public void updateDocument() throws Exception{
Document document = new Document();
document.add(new TextField("name","更新后的内容1", Field.Store.YES));
document.add(new TextField("name2","更新后的内容2", Field.Store.YES));
document.add(new TextField("name3","更新后的内容3", Field.Store.YES));
indexWriter.updateDocument(new Term("name","spring"),document);
indexWriter.close();
}
}

猜你喜欢

转载自www.cnblogs.com/newcityboy/p/12198345.html
今日推荐