案例演示
新建java項(xiàng)目镰禾,命名
lucene
新建
lib
目錄,導(dǎo)入
commons-io-2.4.jar
文件IO的jar包
junit-4.9.jar
junit測(cè)試
lucene-analyzers-common-4.10.3.jar
分詞的jar包
lucene-core-4.10.3.jar
核心的jar包
lucene-queryparser-4.10.3.jar
查詢(xún)的jar包創(chuàng)建索引
package cn.huahcao.lucene;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
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.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class IndexManagerTest {
@Test
public void testCreateIndex() throws Exception{
//采集文件系統(tǒng)中的文檔數(shù)據(jù)顾腊,放入lucene中
//文檔列表粤铭,保存Document
List<Document> docList = new ArrayList<Document>();
//指定文件所在的目錄
File dir = new File("G:\\Java\\JavaEE\\09_SSM\\lucene_day01\\參考資料\\searchsource");
//循環(huán)取出文件
for (File file:dir.listFiles()){
//文件名稱(chēng)
String fileName = file.getName();
//文件內(nèi)容
String fileContent = FileUtils.readFileToString(file);
//文件大小
Long fileSize = FileUtils.sizeOf(file);
//文檔對(duì)象。文件系統(tǒng)中的一個(gè)文件就是一個(gè)Document對(duì)象
Document doc = new Document();
/**
* 第一個(gè)參數(shù):域名
* 第二個(gè)參數(shù):域值
* 第三個(gè)參數(shù):是否存儲(chǔ)杂靶,是為Yes,不存儲(chǔ)為No
*/
TextField nameField = new TextField("fileName",fileName, Field.Store.YES);
TextField contentField = new TextField("fileContent",fileContent, Field.Store.YES);
TextField sizeField = new TextField("fileSize",fileSize.toString(), Field.Store.YES);
//將所有的域存入文檔中
doc.add(nameField);
doc.add(contentField);
doc.add(sizeField);
//將文檔存入文檔集合中
docList.add(doc);
}
//創(chuàng)建分詞器,StandardAnalyzer標(biāo)準(zhǔn)分詞器,標(biāo)準(zhǔn)分詞器對(duì)英文分詞效果很好,對(duì)中文是單字分詞
StandardAnalyzer analyzer = new StandardAnalyzer();
//指定索引和文檔存儲(chǔ)的目錄
FSDirectory directory = FSDirectory.open(new File("G:\\Java\\JavaEE\\09_SSM\\lucene_day01\\tmp"));
//創(chuàng)建寫(xiě)對(duì)象的初始化對(duì)象
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_3,analyzer);
//創(chuàng)建索引和文檔寫(xiě)對(duì)象
IndexWriter indexWriter = new IndexWriter(directory , config);
//將文檔加入到索引和文檔的寫(xiě)對(duì)象中
for (Document doc:docList){
indexWriter.addDocument(doc);
}
//提交
indexWriter.commit();
//關(guān)閉流
indexWriter.close();
}
}
運(yùn)行上面的testCreateIndex()梆惯,生成索引
使用工具luke查看
-
打開(kāi)luke所在目錄
luke所在的目錄不能保護(hù)中午和空格
luke所在的目錄不能保護(hù)中午和空格 -
運(yùn)行工具
java -jar lukeall-4.10.3.jar
java -jar lukeall-4.10.3.jar
運(yùn)行 -
打開(kāi)的界面如下
設(shè)置為索引所在的目錄酱鸭,然后點(diǎn)擊OK
注意選擇FSDirectory,因?yàn)槲覀兇a中使用的是FSDirectory垛吗。
-
打開(kāi)了索引查看的界面
-
顯示某個(gè)Field的分詞情況
-
查看Document
-
搜索