当前位置:首页 > Web开发 > 正文

new IndexWriterConfig()) ; //3、读取磁盘上的文件

2024-03-31 Web开发

标签:

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

lucene中创建索引库

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/31518.html