import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.CorruptIndexException;
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;
/**
* Lucene 工具类
*
* @author seawind
*
*/
public class LuceneUtils {
private static IndexWriter indexWriter;
private static Directory directory;
private static Analyzer analyzer = new IKAnalyzer();
static {
try {
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_36, analyzer);
directory = FSDirectory.open(new File("index"));
indexWriter = new IndexWriter(directory, indexWriterConfig);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
// 关闭索引库
indexWriter.close();
System.out.println("索引库 关闭...");
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
// 返回IndexWriter
public static IndexWriter getIndexWriter() {
return indexWriter;
}
// 返回 IndexSearcher
public static IndexSearcher getIndexSearcher() throws Exception {
return new IndexSearcher(IndexReader.open(directory));
}
}
Lucene 工具类
最新推荐文章于 2023-02-12 16:01:02 发布