Lucene初学Demo

来源:互联网 发布:淘宝1111购物狂欢节 编辑:程序博客网 时间:2024/05/05 13:15

初次使用Lucene先从最简单的实例入手。

不跟你多BB,直接上代码:

这个Demo是使用Maven构建的。

创建Lucene索引的Indexer类:

package com.java.lucene;import java.io.File;import java.io.FileReader;import java.nio.file.Paths;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.standard.StandardAnalyzer;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.store.Directory;import org.apache.lucene.store.FSDirectory;/** * 创建Lucene索引的类 * @author Administrator * */public class Indexer {// 写索引实例private IndexWriter writer; /** * 构造方法  * 实例化IndexWriter * @param indexDir * @throws Exception */public Indexer(String indexDir)throws Exception{Directory dir=FSDirectory.open(Paths.get(indexDir));// 标准分词器Analyzer analyzer=new StandardAnalyzer(); IndexWriterConfig iwc=new IndexWriterConfig(analyzer);writer=new IndexWriter(dir, iwc);}/** * 关闭写索引 * 也需要释放资源 * @throws Exception */public void close()throws Exception{writer.close();}/** * 索引指定目录的所有文件 * @param dataDir  需要进行索引的目录 * @throws Exception */public int index(String dataDir)throws Exception{//遍历索引目录下的所有文件File []files=new File(dataDir).listFiles();for(File f:files){indexFile(f);}//返回索引的文件数量return writer.numDocs();}/** * 索引指定文件 * @param f */private void indexFile(File f) throws Exception{System.out.println("索引文件:"+f.getCanonicalPath());//这里有一个概念:索引的时候,它会像数据里行和列一样//一行、一行,这里一行就是一个Document,一个文档,文档里又有列Document doc=getDocument(f);writer.addDocument(doc);}/** * 获取文档,文档里再设置每个字段 * @param f */private Document getDocument(File f)throws Exception {Document doc=new Document();doc.add(new TextField("contents",new FileReader(f)));doc.add(new TextField("fileName", f.getName(),Field.Store.YES));//fullPath 完整路径doc.add(new TextField("fullPath",f.getCanonicalPath(),Field.Store.YES));return doc;}/** * 测试创建索引 * @param args */public static void main(String[] args) {//索引输出目录String indexDir="D:\\lucene";//读取数据的路径String dataDir="D:\\lucene\\data";Indexer indexer=null;int numIndexed=0;long start=System.currentTimeMillis();try {indexer = new Indexer(indexDir);numIndexed=indexer.index(dataDir);} catch (Exception e) {e.printStackTrace();}finally{try {indexer.close();} catch (Exception e) {e.printStackTrace();}}long end=System.currentTimeMillis();System.out.println("创建索引:"+numIndexed+" 个文件 花费了"+(end-start)+" 毫秒");}}

运行结果如下:

索引文件:D:\lucene\data\CHANGES.txt索引文件:D:\lucene\data\JRE_VERSION_MIGRATION.txt索引文件:D:\lucene\data\LICENSE.txt索引文件:D:\lucene\data\MIGRATE.txt索引文件:D:\lucene\data\NOTICE.txt索引文件:D:\lucene\data\README.txt索引文件:D:\lucene\data\SYSTEM_REQUIREMENTS.txt创建索引:7 个文件 花费了2036 毫秒


测试查询Lucene的Searcher类:

package com.java.lucene;import java.nio.file.Paths;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.index.DirectoryReader;import org.apache.lucene.index.IndexReader;import org.apache.lucene.queryparser.classic.QueryParser;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.TopDocs;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;/** * 测试查询Lucene 索引的类 * @author Administrator * */public class Searcher {public static void search(String indexDir,String q)throws Exception{Directory dir=FSDirectory.open(Paths.get(indexDir));//创建索引读取器IndexReader reader=DirectoryReader.open(dir);//创建索引查询器IndexSearcher is=new IndexSearcher(reader);// 标准分词器Analyzer analyzer=new StandardAnalyzer(); //开始查询解析QueryParser parser=new QueryParser("contents", analyzer);Query query=parser.parse(q);long start=System.currentTimeMillis();TopDocs hits=is.search(query, 10);long end=System.currentTimeMillis();System.out.println("匹配 "+q+" ,总共花费"+(end-start)+"毫秒"+"查询到"+hits.totalHits+"个记录");for(ScoreDoc scoreDoc:hits.scoreDocs){Document doc=is.doc(scoreDoc.doc);System.out.println(doc.get("fullPath"));}reader.close();}public static void main(String[] args) {//索引存放路径String indexDir="D:\\lucene";//查询字段String q="Zygmunt Saloni";try {search(indexDir,q);} catch (Exception e) {e.printStackTrace();}}}
运行结果如下:

匹配 Zygmunt Saloni ,总共花费32毫秒查询到1个记录D:\lucene\data\LICENSE.txt

代码中出现的读取的数据文件,我和源码一起打包上传了:

下载地址:https://pan.baidu.com/s/1dEG1z4t (我百度网盘分享的如果失效可以扣我。大笑



1 0