Creating an index - Lucene self-Way (c)

Disclaimer: This article is a blogger original article, please respect the original, without bloggers allow prohibited reproduced, reserved the right to pursue https://blog.csdn.net/qq_29914837/article/details/90513812

First, demand analysis shows

There is a news and information in the database table, now we need to create an index file to this table data to support fast full-text search capabilities.

As shown below in Table
Here Insert Picture Description

Second, creating a LuceneUtil, Lucene encapsulates objects corresponding to index the operation.

package com.springboot.main.eimm.search.util;

import java.io.File;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

/**
 * 
 * @method Lucene索引操作对象工具类
 * @author Mr yi
 * @time 2019年5月23日
 */
public class LuceneUtils {

    private static Directory directory  = null;

    private static IndexWriterConfig indexWriterConfig = null; 

    private static Analyzer analyzer = null;
    
    private static Version matchVersion = null;
    
    //static 代码块随着类的加载,只加载一次。作用是初始化类。
    static{
        try {
        	//在 6.6 以上版本中 version 不再是必要的,并且,存在无参构造方法,可以直接使用默认的 StandardAnalyzer 分词器。
            matchVersion = Version.LUCENE_8_1_0;
            //索引存放的位置,设置在当前目录中(项目根路径下)
            final String INDEXURL = "./index_dir/search";
            directory = FSDirectory.open(new File(INDEXURL).toPath());
            //analyzer = new StandardAnalyzer(); // 标准分词器,适用于英文[支持中文采用的方法为单字切分。他会将词汇单元转换成小写形式,并去除停用词和标点符号]
            //analyzer = new SmartChineseAnalyzer();//中文分词
            //analyzer = new ComplexAnalyzer();//中文分词
        	//analyzer = new IKAnalyzer();//中文分词
             analyzer = new IKAnalyzer();//中文分词
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Directory getDirectory() {
        return directory;
    }

    /**
     * 
     * @method 返回用于操作索引的对象
     * @author Mr yi
     * @time 2019年5月23日
     * @return
     * @throws Exception
     */
    public static IndexWriter getIndexWriter() throws Exception{
    	//创建索引写入配置
        indexWriterConfig = new IndexWriterConfig(analyzer);
        //创建索引写入对象
        IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
        return indexWriter;
    }

    /**
     * 
     * @method 返回用于读取索引的对象
     * @author Mr yi
     * @time 2019年5月23日
     * @return
     * @throws Exception
     */
    public static IndexSearcher getIndexSearcher() throws Exception{
        IndexReader indexReader  = DirectoryReader.open(directory);
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        return indexSearcher;
    }

    /**
     * 
     * @method 返回当前版本
     * @author Mr yi
     * @time 2019年5月23日
     * @return
     */
    public static Version getMatchVersion() {
        return matchVersion;
    }

    /**
     * 
     * @method 返回当前使用的分词器
     * @author Mr yi
     * @time 2019年5月23日
     * @return
     */
    public static Analyzer getAnalyzer() {
        return analyzer;
    }
    
    
  
 
}

Third, create SearchUtils, a package indexing operation method

   /**
	 * 
	 * @method 将Article数据转换为Document
	 * @author Mr yi
	 * @time 2019年5月23日
	 * @param article 对象
	 * @return
	 */
	public static  Document articleToDocument(Article article ){
		 
		if(article==null)
		return null;
		
	    Document document = new Document();
	    IndexableField idField = new StringField("id",article.getId(),Store.YES);
	    IndexableField titleField = new StringField("artitle_title",article.getArtitle_title(),Store.YES);
	    IndexableField contentField = new TextField("artitle_content",article.getArtitle_content(),Store.YES);
	    IndexableField urlField = new StringField("artitle_url",article.getArtitle_url(),Store.YES);
	    IndexableField authorField = new StringField("artitle_author",article.getArtitle_author(),Store.YES);
	    IndexableField stateField = new StringField("artitle_state",article.getArtitle_state(),Store.YES);
	    IndexableField typeField = new StringField("artitle_type",article.getArtitle_type(),Store.YES);
	    
	    document.add(idField);  
	    document.add(titleField);  
	    document.add(contentField); 
	    document.add(urlField);  
	    document.add(authorField);
	    document.add(stateField);  
	    document.add(typeField);  
	    return document;
	}

   /**
	 * 
	 * @method 添加索引
	 * @author Mr yi
	 * @time 2019年5月24日
	 * @param document
	 * @throws Exception
	 */
    public static void addIndex(Document document) throws Exception{
        //获取indexWrite对象
        IndexWriter indexWriter =  LuceneUtils.getIndexWriter();
        try {
        	 //将document写入磁盘中
            indexWriter.addDocument(document);
        }finally {//定要注意关闭indexWrite. 包括异常下,用finally关闭.否则会导致下一次写索引失败.,修改程序后,直接删除write.lock文件后就可以
        	indexWriter.close();
        }
       
        
    }

Fourth, creating class instances SearchServiceImpl service, includes creating an index operation, DAO layer does not provide specific implementation

/**
 * 添加索引
 * @param article
 * @throws Exception 
 */
@Override
public void addIndex() throws Exception{
	IndexWriter indexWriter =  LuceneUtils.getIndexWriter();
	Artitle artitle  = new Artitle (); //这里需要给artitle 对象赋值 
    Document document = SearchUtils.articleToDocument(artitle);
    SearchUtils.addIndex(document);
 
}

Fifth, and finally call control layer addIndex () method, or you can write the test class, find the index file will be found under index_dir folder under the root directory of the project after the success.

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/qq_29914837/article/details/90513812