案例演示
新建java項目,命名
lucene
新建
lib
目錄,導入
commons-io-2.4.jar
文件IO的jar包
junit-4.9.jar
junit測試
lucene-analyzers-common-4.10.3.jar
分詞的jar包
lucene-core-4.10.3.jar
核心的jar包
lucene-queryparser-4.10.3.jar
查詢的jar包創建索引
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{
//采集文件系統中的文檔數據,放入lucene中
//文檔列表,保存Document
List<Document> docList = new ArrayList<Document>();
//指定文件所在的目錄
File dir = new File("G:\\Java\\JavaEE\\09_SSM\\lucene_day01\\參考資料\\searchsource");
//循環取出文件
for (File file:dir.listFiles()){
//文件名稱
String fileName = file.getName();
//文件內容
String fileContent = FileUtils.readFileToString(file);
//文件大小
Long fileSize = FileUtils.sizeOf(file);
//文檔對象。文件系統中的一個文件就是一個Document對象
Document doc = new Document();
/**
* 第一個參數:域名
* 第二個參數:域值
* 第三個參數:是否存儲,是為Yes,不存儲為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);
}
//創建分詞器,StandardAnalyzer標準分詞器,標準分詞器對英文分詞效果很好,對中文是單字分詞
StandardAnalyzer analyzer = new StandardAnalyzer();
//指定索引和文檔存儲的目錄
FSDirectory directory = FSDirectory.open(new File("G:\\Java\\JavaEE\\09_SSM\\lucene_day01\\tmp"));
//創建寫對象的初始化對象
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_3,analyzer);
//創建索引和文檔寫對象
IndexWriter indexWriter = new IndexWriter(directory , config);
//將文檔加入到索引和文檔的寫對象中
for (Document doc:docList){
indexWriter.addDocument(doc);
}
//提交
indexWriter.commit();
//關閉流
indexWriter.close();
}
}
運行上面的testCreateIndex(),生成索引
使用工具luke查看
-
打開luke所在目錄
luke所在的目錄不能保護中午和空格
luke所在的目錄不能保護中午和空格 -
運行工具
java -jar lukeall-4.10.3.jar
java -jar lukeall-4.10.3.jar
運行 -
打開的界面如下
設置為索引所在的目錄,然后點擊OK
注意選擇FSDirectory,因為我們代碼中使用的是FSDirectory。
-
打開了索引查看的界面
-
顯示某個Field的分詞情況
-
查看Document
-
搜索