1.Lucene的入門案例:
創(chuàng)建索引
環(huán)境:
需要下載Lucene
http://lucene.apache.org
最低要求jdk1.8
工程搭建:
創(chuàng)建一個java工程
添加jar:
lucene-analyzers-common-7.4.0.jar
lucene-core-7.4.0.jar
commons-io.jar
步驟 :
1.創(chuàng)建一個Director對象,指定索引庫的位置随橘。
2.基于Directory對象來創(chuàng)建一個indexWriter對象
3.讀取磁盤上的文件闷串,對應(yīng)每個文件創(chuàng)建一個文檔對象死陆。
4.向文檔對象中添加域
5.把文檔對象寫入索引庫
6.關(guān)閉indexWriter對象
package com.itheima;
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;
/**
* @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)建一個Director對象,指定索引庫的位置盲厌。
//把索引保存在內(nèi)存中
// Directory dictionary=new RAMDirectory();
//把索引保存在磁盤中
Directory directory= FSDirectory.open(new File("E:\\Desktop").toPath());
// 2.基于Directory對象來創(chuàng)建一個indexWriter對象
IndexWriter indexWriter=new IndexWriter(directory,new IndexWriterConfig());
// 3.讀取磁盤上的文件燎孟,對應(yīng)每個文件創(chuàng)建一個文檔對象。
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:是否儲存
Field fieldName=new TextField("name",file1Name, Field.Store.YES);
Field fieldPath=new TextField("path",path, Field.Store.YES);
Field fieldContext=new TextField("context",fileContext, Field.Store.YES);
Field fieldSize=new TextField("size",size+"", Field.Store.YES);
//創(chuàng)建文檔對象
Document document=new Document();
// 4.向文檔對象中添加域
document.add(fieldName);
document.add(fieldPath);
document.add(fieldContext);
document.add(fieldSize);
// 5.把文檔對象寫入索引庫
indexWriter.addDocument(document);
}
// 6.關(guān)閉indexWriter對象
indexWriter.close();
}
}
2.使用luke查看索引庫中的內(nèi)容:
運(yùn)行之后可以看到因?yàn)槲冶4娴牡刂肥亲烂?因此我的桌面上多了這么一排文件.即剛剛通過代碼生成的索引庫岸裙,那么我們怎么查看這些索引庫呢?用luke,不過值得注意的是luke是通過java編寫的工具,需要JDK1.9版本才能啟動,這里就不做演示了,我把包上傳,有需要的可以自行下載研究.
image.png