☰
1 创建索引
2026/10/21 7:47:52 网站建设 项目流程

1. 新建java工程

2. 新建一个Java文件

packagecom.simon;importorg.apache.lucene.analysis.standard.StandardAnalyzer;importorg.apache.lucene.document.Document;importorg.apache.lucene.document.Field;importorg.apache.lucene.index.IndexWriter;importorg.apache.lucene.index.IndexWriterConfig;importorg.apache.lucene.store.Directory;importorg.apache.lucene.store.FSDirectory;importorg.apache.lucene.store.RAMDirectory;importorg.apache.lucene.util.Version;importjava.io.File;importjava.io.FileReader;importjava.io.IOException;publicclassHelloLucene{/** * 建立索引 */publicvoidindex()throwsIOException{//1.创建Directory/** * 将索引库创建在内存中 *///Directory directory = new RAMDirectory();//讲索引库创建在硬盘上Directorydirectory=FSDirectory.open(newFile("d:/lucene/index01"));//2.创建IndexWriter//由于兼容性的问题,必须指定一个版本号,以及对应的分词器IndexWriterConfigiwc=newIndexWriterConfig(Version.LUCENE_35,newStandardAnalyzer(Version.LUCENE_35));IndexWriterwriter=null;try{writer=newIndexWriter(directory,iwc);//3.0版本之后的创建方式//3.创建DocumentDocumentdoc=null;Filef=newFile("d:/lucene/example");for(Filefile:f.listFiles()){//4.为Document创建field//先存储文件的路径和文件的名称//Field.Store.YES 表示需要存储//Field.Index.NOT_ANALYZED 表示不需要分词doc=newDocument();doc.add(newField("content",newFileReader(file)));doc.add(newField("filename",file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED));doc.add(newField("path",file.getAbsolutePath(),Field.Store.YES,Field.Index.NOT_ANALYZED));//5.通过IndexWriter添加文档到索引中writer.addDocument(doc);}}catch(IOExceptione){thrownewRuntimeException(e);}finally{if(writer!=null){try{writer.close();}catch(IOExceptione){thrownewRuntimeException(e);}}}}}
packagecom.simon;importorg.junit.Test;importjava.io.IOException;publicclassTestIndex{@TestpublicvoidcreateIndex()throwsIOException{HelloLucenehl=newHelloLucene();hl.index();}}

注意:文件中的d盘中的txt是原始文件,为了创建document新建,索引库index01则由程序创建


需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询