Lucene入門

1.功能

實(shí)現(xiàn)全文檢索。
生活中遇到兩類數(shù)據(jù):結(jié)構(gòu)化數(shù)據(jù)(例如數(shù)據(jù)庫)和非結(jié)構(gòu)化數(shù)據(jù)(例如電腦磁盤下一堆文檔文件)。對于結(jié)構(gòu)化數(shù)據(jù)查詢速度非???,但對于非結(jié)構(gòu)化數(shù)據(jù)檢索起來束手無策。借鑒結(jié)構(gòu)化數(shù)據(jù)檢索的思想,可以將文檔結(jié)構(gòu)化(建立索引)從而進(jìn)行全文檢索。

2.流程 (索引 和 搜索)

全文檢索流程圖

3.具體過程

3.1 創(chuàng)建索引:

3.1.1.獲得原始文檔:磁盤讀取
3.1.2.創(chuàng)建文檔對象:原始文檔 ---> Document (一個一個的域(Name,Value對)

Document長這樣

同一個文檔可以 有不同的域, 不同的文檔可以有相同的域。每個文檔有唯一的編號。
3.1.3.分析文檔:
對域中內(nèi)容進(jìn)行分析。分析過程是經(jīng)過對原始文檔提取單詞,將字母轉(zhuǎn)小寫,去標(biāo)點(diǎn)等最終生成一個個語匯單元(就是一個個單詞)的過程。這里的一個單詞成為一個term,term實(shí)質(zhì)上是<Key value>的形式<域名,單詞內(nèi)容>。例如Term1:<file_content,spring>;Term2<file_name,spring>.這些term就是索引。
3.1.4.創(chuàng)建索引:
![image](http://upload-images.jianshu.io/upload_images/7778847-3c695fa5c3073c57.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

倒排索引:

倒排索引表長這樣

3.2 查詢索引:

3.2.1 用戶查詢接口界面


查詢接口界面

3.2.2 創(chuàng)建查詢

語法“fileName:lucene”

3.2.3 執(zhí)行查詢

查詢語句中的關(guān)鍵詞作為term,去倒排索引表中查找文檔ID列表

3.2.4 渲染結(jié)果


代碼開發(fā)部分


1. 配置開發(fā)環(huán)境

1.1 Lucene下載
地址: http://lucene.apache.org/
版本:lucene4.10.3
JDK:1.7+
IDE: eclipse
1.2 使用的Jar包
Lucene包:
lucene-analyzers-common-4.10.3.jar
lucene-analyzers-smartcn-4.10.3.jar
lucene-core-4.10.3.jar
lucene-queryparser-4.10.3.jar
其他:
commons-io-2.4.jar
IKAnalyzer2012FF_u1.jar
junit-4.9.jar

2. 創(chuàng)建索引庫

使用indexwriter對象創(chuàng)建索引
2.1 實(shí)現(xiàn)步驟:
第一步:創(chuàng)建Java project,導(dǎo)包
第二步:創(chuàng)建一個indexwriter對象
1)指定索引庫存放位置Directory對象
2)指定一個分析器,對文檔內(nèi)容進(jìn)行分析
第三步:創(chuàng)建Document對象
第四步:創(chuàng)建field,將field添加到Document
第五步:使用indexwriter對象將Document對象寫入索引庫,此過程進(jìn)行索引創(chuàng)建。并將索引和Document對象寫入索引庫
第六步:關(guān)閉indexwriter對象

package com.itheima.lucene;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StoredField;
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.apache.lucene.util.Version;
import org.junit.Test;

/*
 * Lucene入門
 * 創(chuàng)建索引,查詢索引
 * */
public class FirstLucene {
    
    @Test
    public void testIndex() throws Exception{
//      第一步:創(chuàng)建Java project,導(dǎo)包
//      第二步:創(chuàng)建一個indexwriter對象
        Directory directory = FSDirectory.open(new File("D:\\temp\\index"));
        Analyzer analyzer = new StandardAnalyzer();
        IndexWriterConfig config = new IndexWriterConfig(Version.LATEST,analyzer);
        IndexWriter indexWriter = new IndexWriter(directory,config);
//                    1)指定索引庫存放位置Directory對象
//                    2)指定一個分析器,對文檔內(nèi)容進(jìn)行分析

//      第四步:創(chuàng)建field,將field添加到Document
        File f = new File("E:\\Lucene&solr\\searchsource");
        File[] listFiles = f.listFiles();
        for(File file:listFiles){
//          第三步:創(chuàng)建Document對象
            Document document = new Document();
            
            //文件名稱
            String file_name = file.getName();//Y,Y,X
            Field fileNameField = new TextField("fileName",file_name,Store.YES);
    
            //文件大小
            long file_size = FileUtils.sizeOf(file);
            Field fileSizeField = new LongField("fileSize",file_size,Store.YES);
            
            //文件路徑
            String file_path = file.getPath(); //N,N,Y
            Field filePathField = new StoredField("filePath",file_path);
            
            //文件內(nèi)容
            String file_content = FileUtils.readFileToString(file);//Y,Y,X
            Field fileContentField = new TextField("fileContent",file_content,Store.NO);
            
            document.add(fileNameField);  
            document.add(fileSizeField);
            document.add(filePathField);
            document.add(fileContentField);
//          第四步:使用indexwriter對象將Document對象寫入索引庫,此過程進(jìn)行索引創(chuàng)建。并將索引和Document對象寫入索引庫
            indexWriter.addDocument(document);
        }

//      第六步:關(guān)閉indexwriter對象
        indexWriter.close();
    }
}

3. 查詢索引

3.1 實(shí)現(xiàn)步驟:
第一步:創(chuàng)建一個Directory對象,也就是索 引庫的位置
第二步:創(chuàng)建一個indexReader對象,需要制定Directory對象(該對象用來和索引庫溝通)
第三步:創(chuàng)建一個indexsearcher對象,需要制定indexReader對象 (基于流的搜索)
第四步:創(chuàng)建一個TermQuery對象,指定查詢的域和查詢的關(guān)鍵詞
第五步:執(zhí)行查詢
第六步:返回查詢結(jié)果,遍歷結(jié)果并輸出
第七步:關(guān)閉IndexReader對象

@Test
    public void testSearch() throws Exception{
//      第一步:創(chuàng)建一個Directory對象,也就是索 引庫的位置
        Directory directory = FSDirectory.open(new File("D:\\temp\\index")); //磁盤上的庫
//      第二步:創(chuàng)建一個indexReader對象,需要制定Directory對象(該對象用來和索引庫溝通)
        IndexReader indexReader = DirectoryReader.open(directory);
//      第三步:創(chuàng)建一個indexsearcher對象,需要制定indexReader對象 (基于流的搜索)
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
//      第四步:創(chuàng)建一個TermQuery對象,指定查詢的域和查詢的關(guān)鍵詞
        TermQuery query = new TermQuery(new Term("fileContent","spring"));
//      第五步:執(zhí)行查詢
        TopDocs topDocs = indexSearcher.search(query, 2); 
//      第六步:返回查詢結(jié)果,遍歷結(jié)果并輸出
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for(ScoreDoc scoreDoc : scoreDocs){
            int doc = scoreDoc.doc;
            Document document = indexSearcher.doc(doc);
            String fileName = document.get("fileName");
            System.out.println(fileName);
            String fileContent = document.get("fileContent");
            System.out.println(fileContent);
            String fileSize = document.get("fileSize");
            System.out.println(fileSize);
            String filePath = document.get("filePath");
            System.out.println(filePath);
            System.out.println("-------------");
        }
//      第七步:關(guān)閉IndexReader對象
        indexReader.close();
    }

4.支持中文分詞

IKAnalyzer使用,可擴(kuò)展
1.導(dǎo)包
2.在src下放入


IKAnalyzer使用需要放入的文件

查看中文分詞器的使用效果

@Test
    public void testTokenStream() throws Exception {
        // 創(chuàng)建一個標(biāo)準(zhǔn)分析器對象
//      Analyzer analyzer = new StandardAnalyzer();
//      Analyzer analyzer = new CJKAnalyzer();
//      Analyzer analyzer = new SmartChineseAnalyzer();
        Analyzer analyzer = new IKAnalyzer();
        // 獲得tokenStream對象
        // 第一個參數(shù):域名,可以隨便給一個
        // 第二個參數(shù):要分析的文本內(nèi)容
//      TokenStream tokenStream = analyzer.tokenStream("test",
//              "The Spring Framework provides a comprehensive programming and configuration model.");
        TokenStream tokenStream = analyzer.tokenStream("test",
                "高富帥可以用二維表結(jié)構(gòu)來邏輯表達(dá)實(shí)現(xiàn)的數(shù)據(jù)");
        // 添加一個引用,可以獲得每個關(guān)鍵詞
        CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);
        // 添加一個偏移量的引用,記錄了關(guān)鍵詞的開始位置以及結(jié)束位置
        OffsetAttribute offsetAttribute = tokenStream.addAttribute(OffsetAttribute.class);
        // 將指針調(diào)整到列表的頭部
        tokenStream.reset();
        // 遍歷關(guān)鍵詞列表,通過incrementToken方法判斷列表是否結(jié)束
        while (tokenStream.incrementToken()) {
            // 關(guān)鍵詞的起始位置
            System.out.println("start->" + offsetAttribute.startOffset());
            // 取關(guān)鍵詞
            System.out.println(charTermAttribute);
            // 結(jié)束位置
            System.out.println("end->" + offsetAttribute.endOffset());
        }
        tokenStream.close();
    }

5.Lucene所以庫查詢(詳細(xì))

5.1使用Query子類查詢

5.1.1 MatchAllDocsQuery --- 查詢索引目錄中的所有文檔

public IndexSearcher getIndexSearch() throws Exception{
//      第一步:創(chuàng)建一個Directory對象,也就是索 引庫的位置
        Directory directory = FSDirectory.open(new File("D:\\temp\\index")); //磁盤上的庫
//      第二步:創(chuàng)建一個indexReader對象,需要制定Directory對象(該對象用來和索引庫溝通)
        IndexReader indexReader = DirectoryReader.open(directory);
//      第三步:創(chuàng)建一個indexsearcher對象,需要制定indexReader對象 (基于流的搜索)
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        return indexSearcher;
    }
    public void printResult(IndexSearcher indexSearcher,MatchAllDocsQuery query) throws Exception{
        //第五步:執(zhí)行查詢
        TopDocs topDocs = indexSearcher.search(query, 2); 
//      第六步:返回查詢結(jié)果,遍歷結(jié)果并輸出
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for(ScoreDoc scoreDoc : scoreDocs){
            int doc = scoreDoc.doc;
            Document document = indexSearcher.doc(doc);
            String fileName = document.get("fileName");
            System.out.println(fileName);
            String fileContent = document.get("fileContent");
            System.out.println(fileContent);
            String fileSize = document.get("fileSize");
            System.out.println(fileSize);
            String filePath = document.get("filePath");
            System.out.println(filePath);
            System.out.println("-------------");
        }
    }
    // 查詢所有
    @Test
    public void testMatchAllDocsQuery() throws Exception{
        IndexSearcher indexSearcher = getIndexSearch();
        MatchAllDocsQuery query = new MatchAllDocsQuery();
        printResult(indexSearcher,query);
        indexSearcher.getIndexReader().close();
        
    }

5.1.2 TermQuery --- 精準(zhǔn)查詢
5.1.3 NumericRangeQuery --- 根據(jù)數(shù)值范圍查詢

//根據(jù)數(shù)值范圍查詢
    @Test
    public void testNumericRangeQuery() throws Exception {
        IndexSearcher indexSearcher = getIndexSearcher();
        
        Query query = NumericRangeQuery.newLongRange("fileSize", 47L, 200L, false, true);
        System.out.println(query);
        printResult(indexSearcher, query);
        //關(guān)閉資源
        indexSearcher.getIndexReader().close();
    }

5.1.3 BooleanQuery --- 組合查詢

@Test
    public void testBooleanQuery() throws Exception {
        IndexSearcher indexSearcher = getIndexSearcher();
        
        BooleanQuery booleanQuery = new BooleanQuery();
        
        Query query1 = new TermQuery(new Term("fileName","apache"));
        Query query2 = new TermQuery(new Term("fileName","lucene"));
        //  select * from user where id =1 or name = 'safdsa'
        booleanQuery.add(query1, Occur.MUST);
        booleanQuery.add(query2, Occur.SHOULD);
        System.out.println(booleanQuery);
        printResult(indexSearcher, booleanQuery);
        //關(guān)閉資源
        indexSearcher.getIndexReader().close();
    }
5.2使用queryparser查詢

通過queryparser創(chuàng)建query

//條件解釋的對象查詢
    @Test
    public void testQueryParser() throws Exception {
        IndexSearcher indexSearcher = getIndexSearcher();
        //參數(shù)1: 默認(rèn)查詢的域  
        //參數(shù)2:采用的分析器
        QueryParser queryParser = new QueryParser("fileName",new IKAnalyzer());
        // *:*   域:值
        Query query = queryParser.parse("fileName:lucene is apache OR fileContent:lucene is apache");
        
        printResult(indexSearcher, query);
        //關(guān)閉資源
        indexSearcher.getIndexReader().close();
    }

總結(jié)

1.案例:磁盤的文件(文件內(nèi)容)
2.為什么要用全文檢索?
結(jié)構(gòu)化數(shù)據(jù) vs 非結(jié)構(gòu)化數(shù)據(jù)
3.什么是全文檢索?
4.全文檢索的實(shí)現(xiàn)手段
5.Lunce是什么?
6.Lunce的使用?實(shí)現(xiàn)流程?
創(chuàng)建索引:
查詢索引:
7.創(chuàng)建索引的代碼實(shí)現(xiàn)
8.查詢索引的代碼實(shí)現(xiàn)
9.中文分詞器
標(biāo)準(zhǔn)分析器
cjk分析器
Smart分析器
IK分析器(重點(diǎn))
10.中文分詞器使用時機(jī):創(chuàng)建索引IK,查詢索引IK
11.索引的維護(hù):增刪改
12.查詢索引:
子類查詢
Queryparse



代碼地址:https://github.com/yunqinz/LuceneStarted

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容