一.Lucene基礎
Lucene是apache軟件基金會4 jakarta項目組的一個子項目,是一個開放源代碼的全文檢索引擎工具包,但它不是一個完整的全文檢索引擎,而是一個全文檢索引擎的架構,提供了完整的查詢引擎和索引引擎,部分文本分析引擎(英文與德文兩種西方語言)。Lucene的目的是爲軟件開發人員提供一個簡單易用的工具包,以方便的在目標系統中實現全文檢索的功能,或者是以此爲基礎建立起完整的全文檢索引擎。Lucene是一套用於全文檢索和搜尋的開源程式庫,由Apache軟件基金會支持和提供。Lucene提供了一個簡單卻強大的應用程式接口,能夠做全文索引和搜尋。在Java開發環境裏Lucene是一個成熟的免費開源工具。就其本身而言,Lucene是當前以及最近幾年最受歡迎的免費Java信息檢索程序庫。人們經常提到信息檢索程序庫,雖然與搜索引擎有關,但不應該將信息檢索程序庫與搜索引擎相混淆。
二.下載
lucene有7個包需要導入:analysis,document,index,queryParser,search,store,util
以下是最常用的:
Lucene-core-5.0.0.jar,其中包括了常用的文檔,索引,搜索,存儲等相關核心代碼
Lucene-analyzers-common-5.0.0.jar,這裏麪包含了各種語言的詞法分析器,用於對文件內容進行關鍵字切分,提取。
Lucene-highlighter-5.0.0.jar,這個jar包主要用於搜索出的內容高亮顯示。
Lucene-queryparser-5.0.0.jar,提供了搜索相關的代碼,用於各種搜索,比如模糊搜索,範圍搜索,等等。
三.索引建立
//以下是將索引放到內存上
//1.創建Directory (索引建立在內存還是硬盤等)
//Directory directory = new RAMDirectory();///創建索引在內存上
Directory directory = new FSDirectory.open(new File("E:/lucene/index"));//創建索引在硬盤上
//2.創建IndexWriter (寫索引)
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
IndexWriter iwriter = new IndexWriter(directory, config);
//3.創建Document對象(文檔或數據庫表等每一個屬性就叫這個文檔的field)
Document doc = new Document();
//4.爲Document添加field
File f = new File("E:/lucene/example");//該文件夾下可能會有很多文件
for(File file:f.listFiles()){
doc = new Document();
doc.add(new Field("content",new FildReader(file)))//將內容添加到索引中
doc.add(new Field("fieldname",file.getName(),Fild.Store.YES,Fild.Index.not_Analyzer))//添加名字,將名字存儲到硬盤上,不做分詞。
doc.add(new Field("path",file.getAbsolutePath(),Fild.Store.YES,Fild.Index.not_Analyzer))//添加文件路徑到索引中,將文件路徑存儲到硬盤上,不做分詞。
iwriter.addDocument(doc);
}
//5.關閉IndexWriter
iwriter.close();//通常放到事務外
四.分詞
五.搜索
//1.創建Directory (索引建立在內存還是硬盤等)
Directory directory = new FSDirectory.open(new File("E:/lucene/index"));//創建索引在硬盤上
//2.創建IndexReader讀索引
IndexReader reader = IndexReader.open("directory ");
//3.根據IndexReader創建IndexSearcher
IndexSearcher searcher = new IndexSearcher("reader");
//4.創建搜索的Query
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
//創建parser來確定要搜索文件的內容,第二個參數表示要搜索的域
QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, analyzer);
//創建query表示搜索域爲content中包含java的文檔
Query query = parser.parse("java");//java是要搜索的詞
//5.根據searcher搜索並返回TopDos
TopDos tds = searcher.search(query,10);//10條
//6.通過TopDo獲取ScoreDos對象
ScoreDos[] sds = tds.scoreDos;
for(ScoreDos sd :sds){
//7.根據searcher和ScoreDos對象獲取具體得Document對象
Document d = searcher.doc(sd.doc);
//8.根據Document對象獲取需要的值
System.out.println(d.get("filename")+"["+d.get("path")+"]")
}
//5.關閉reader
reader.close();//通常放到事務外
六.高級搜索