lucene中创建索引库

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();
}
}

猜你喜欢

转载自www.cnblogs.com/newcityboy/p/12194766.html
今日推荐