使用Lucene的api将索引创建到索引库中

import org.apache.commons.io.FileUtils; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.NumericDocValuesField; 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; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; public class Day01 { public String dataDir="E:\\data"; @Test //1.创建索引 public void createIndex() throws IOException { //01.准备一个写入索引的目录 Path path = Paths.get("./luceneindex/"); //02.将路径与Directory进行绑定 Directory directory=FSDirectory.open(path); //03.这行code在底层默认已经关联绑定了一个StandardAnalyzer 标准分词器 IndexWriterConfig config=new IndexWriterConfig(); //04.给config设置一个模式 Create:每次都抹掉原来的索引文件,重新构建新的索引文件 config.setOpenMode(IndexWriterConfig.OpenMode.CREATE); //05.索引写入器需要两个入参,一个是目录,另一个是配置 IndexWriter writer=new IndexWriter(directory,config); //06.准备加入索引库的内容 File file = new File(dataDir); //07.某个目录下的文件集合 File[] files = file.listFiles(); for (File item:files) { //08.将内容幻化成----->Document Document document=new Document(); String filename=item.getName(); //file--->String String filecontent=FileUtils.readFileToString(item); Long modifydate=item.lastModified(); //09.真正的给Document的field赋值 document.add(new TextField("filename",filename,Field.Store.YES)); document.add(new TextField("filecontent",filecontent,Field.Store.YES)); document.add(new NumericDocValuesField("modifydate",modifydate)); //10.将单个Document(一条记录) 保存到 索引库中 writer.addDocument(document); } //11.关闭索引库 writer.close(); System.out.println("add indexes ok!"); } }

猜你喜欢

转载自www.cnblogs.com/bdqnjs/p/9420863.html