文档详情

经典的lucene实例代码及详细解析以及lucene结构流程介绍..docx

发布:2017-01-20约8.03千字共11页下载文档
文本预览下载声明
本文摘要:本文并给出一个经典的lucene全文收索例子代码。该例子功能是从磁盘文档建立索引,搜索该文档中的哪个TXT文件包含所搜索内容。最后再大致介绍Lucene的结构模块,应用流程希望对网友能有帮助。创建索引代码:package luceneL;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.io.Reader;import java.util.Date;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.index.CorruptIndexException;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.store.LockObtainFailedException;public class createIndex {public static boolean createDocumentIndex(){boolean bool=false;//被索引的目录文件夹File dirpath=new File(E:\\documentTest);//索引文件存放的目录文件夹File indexpath=new File(E:\\Index);//分词,分词有StandardAnalyzer和SimpleAnalyzer两种//lucene是将一句句话,一段话Field,分成一个个词Term进行索引搜索的。Analyzer analyzer=new StandardAnalyzer();try {//向E:\\Index保存建立的索引Index内容//用到IndexWriter类,这里需要传入的三个参数为://(索引目录文件夹,分词)IndexWriter index=new IndexWriter(indexpath,analyzer,true);File[] txtfiles=dirpath.listFiles();long startTime=new Date().getTime();for(int i=0;itxtfiles.length;i++){if(txtfiles[i].isFile()txtfiles[i].getName().endsWith(.txt)){System.out.println(文件+txtfiles[i].getCanonicalPath()+正在索引中。。。);//Read将txt内容存进内存Reader read=new FileReader(txtfiles[i]);//创建Document的实例Document doc=new Document();//将field存进索引的Document//Document添加读取的文章内容(缓存在内存中的文章内容read)doc.add(new Field(content,read));//Document添加文章对应路径信息等 //doc.add(new Field(path,txtfiles[i].getAbsolutePath(),Field.Store.YES,Field.Index.NO));//index加Document,索引创建成功index.addDocument(doc);}}//索引优化optimize(),合并磁盘上的索引文件,以便减少文件的数量,从而也减少搜索索引的时间index.optimize();//注意关闭IndexWriter,立即将索引文件写入到目录磁盘中,生成索引文件index.close();long endTime=new Date().getTime();System.out.println(共花了+(endTime-startTime)+毫秒将文档增加到索引中+indexpath.getPath());bool=true;} catch (CorruptIndexException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (LockObtainFailedException e) {// TODO Auto-generated catc
显示全部
相似文档