全文检索技术---Lucene对索引库的维护管理

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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值