lucene中创建索引库

和自甴很熟 提交于 2020-01-15 01:57:18
package com.hope.lucene;import org.apache.commons.io.FileUtils;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;import org.junit.Test;import java.io.File;/** * @author newcityman * @date 2020/1/15 - 0:01 */public class LuceneFirst {    @Test    public void createIndex() throws  Exception{        //1、创建一个Director对象,指定索引库保存的位置        //把索引库保存到磁盘        Directory directory = FSDirectory.open(new File("G:\\workspace_idea3\\lucene\\temp\\index").toPath());        //2、基于Directory对象,创建一个IndexWriter对象        IndexWriter indexWriter = new IndexWriter(directory,new IndexWriterConfig());        //3、读取磁盘上的文件,对应每个文件创建一个文档对象        File file = new File("G:\\workspace_idea3\\lucene\\temp\\searchsource");        File[] files = file.listFiles();        for (File f : files) {            //取文件名            String fileName = f.getName();            //取文件路径            String filePath = f.getPath();            //取文件内容            String fileContent = FileUtils.readFileToString(f, "utf-8");            //文件大小            long fileSize = FileUtils.sizeOf(f);            //创建Field            TextField fieldName = new TextField("name", fileName, Field.Store.YES);            TextField fieldPath = new TextField("path", filePath, Field.Store.YES);            TextField fieldContent = new TextField("content", fileContent, Field.Store.YES);            TextField fieldSize = new TextField("size", fileSize+"", Field.Store.YES);                        //4、向文档对象中添加Field            //创建文档            Document document = new Document();            document.add(fieldName);            document.add(fieldPath);            document.add(fieldContent);            document.add(fieldSize);            //5、把文档对象写入到索引库中            indexWriter.addDocument(document);        }        //6、关闭indexWriter对象            indexWriter.close();    }}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!