Lucene的工具类

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.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;

//枚举单例方式创建Lucene的工具类
public enum  LuceneUtils {

    INSTANCE;

    private LuceneUtils(){}

    private static String indexPath;

    public Analyzer analyzer = new IKAnalyzer();
    //静态库为静态成员变量初始化值
    static{
        try {
            Properties properties = new Properties();
            properties.load(LuceneUtils.class.getClassLoader().getResourceAsStream("lucene.properties"));
            indexPath = properties.getProperty("lucenen.indexpath");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取IndexWriter
     * @return
     * @throws IOException
     */
    public IndexWriter getIndexWriter() throws IOException {
        //获取IndexWriter
        Directory directory = getDirectory();
        IndexWriterConfig config = new IndexWriterConfig(analyzer);
        IndexWriter indexWriter = new IndexWriter(directory,config);
        return indexWriter;
    }

    /**
     * 获取IndexReader
     * @return
     * @throws IOException
     */
    public IndexReader getIndexReader() throws IOException {
        Directory directory = getDirectory();
        IndexReader reader = DirectoryReader.open(directory);
        return reader;
    }

    /**
     * 获取Directory
     * @return
     * @throws IOException
     */
    private Directory getDirectory() throws IOException {
        Path path = Paths.get(indexPath);
        return FSDirectory.open(path);
    }

}

你可能感兴趣的:(工具)