通過(guò)代碼我們發(fā)現(xiàn),我們所有的索引都是用的TextField方法,我們經(jīng)常要對(duì)索引進(jìn)行增刪改查,如果都是用TextField,比如文件的路徑,我們不會(huì)對(duì)路徑進(jìn)行分詞,是否有索引也沒有那么重要,只需要存儲(chǔ)即可,那么如果這個(gè)時(shí)候還是用TextFiled會(huì)不會(huì)有那么些浪費(fèi)?Field有多種方法,我們來(lái)看一下.
image.png
可以將我們的代碼進(jìn)行改造一下:
package com.itheima;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.document.*;
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 org.wltea.analyzer.lucene.IKAnalyzer;
import java.io.File;
/**
* @ClassName lucene
* @Description TODO
* @Author gkz
* @Date 2019/8/21 18:02
* @Version 1.0
**/
public class luceneFirst {
@Test
public void createIndex() throws Exception{
// 1.創(chuàng)建一個(gè)Director對(duì)象,指定索引庫(kù)的位置。
//把索引保存在內(nèi)存中
// Directory dictionary=new RAMDirectory();
//把索引保存在磁盤中
Directory directory= FSDirectory.open(new File("E:\\Desktop").toPath());
// 2.基于Directory對(duì)象來(lái)創(chuàng)建一個(gè)indexWriter對(duì)象
IndexWriterConfig config=new IndexWriterConfig(new IKAnalyzer());
IndexWriter indexWriter=new IndexWriter(directory,config);
// 3.讀取磁盤上的文件,對(duì)應(yīng)每個(gè)文件創(chuàng)建一個(gè)文檔對(duì)象。
File file=new File("E:\\Desktop\\87.lucene\\lucene\\02.參考資料\\searchsource");
File[] files=file.listFiles();
for (File file1 : files) {
//取文件名
String file1Name=file1.getName();
//文件的路徑
String path=file1.getPath();
//文件的內(nèi)容
String fileContext = FileUtils.readFileToString(file1, "utf-8");
//文件的大小
long size = FileUtils.sizeOf(file1);
//創(chuàng)建Field
//參數(shù)1:域的名稱,參數(shù)2:域的內(nèi)容牲剃,參數(shù)3:是否儲(chǔ)存
Field fieldName=new TextField("name",file1Name, Field.Store.YES);
Field fieldPath=new StoredField("path",path);
Field fieldContext=new TextField("context",fileContext, Field.Store.YES);
Field fieldSizeValue=new LongPoint("size",size);
Field fieldSizeStore=new StoredField("size",size);
//創(chuàng)建文檔對(duì)象
Document document=new Document();
// 4.向文檔對(duì)象中添加域
document.add(fieldName);
document.add(fieldPath);
document.add(fieldContext);
document.add(fieldSizeValue);
document.add(fieldSizeStore);
// 5.把文檔對(duì)象寫入索引庫(kù)
indexWriter.addDocument(document);
}
// 6.關(guān)閉indexWriter對(duì)象
indexWriter.close();
}
}