zoukankan      html  css  js  c++  java
  • 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();
    }
    }
  • 相关阅读:
    (最小生成树) 畅通工程再续 -- HDU --1875
    (最小生成树)Jungle Roads -- HDU --1301
    (最小生成树 )还是畅通工程 -- HDU--1233
    不同版本的 IIS 中使用 ASP.NET MVC(C#)【转】
    我们应当怎样做需求分析【转】
    C# DataTable几个常用的查询表达式【转】
    C# DataTable转实体 通用方法【转】
    C# 如何利用反射来加载程序集,并调用程序集中有关类的方法【转】
    IEnumerable和IEnumerator 详解 【转】
    循环对XML文档添加Attribute以及移除Element 【转】
  • 原文地址:https://www.cnblogs.com/newcityboy/p/12198345.html
Copyright © 2011-2022 走看看