1. 程式人生 > >Lucene學習篇之高亮搜尋結果

Lucene學習篇之高亮搜尋結果

前言:


import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;

/**
 * 搜尋結果高亮顯示
 */
public class LunceneHightLighter {

    public static void main(String[] args) throws IOException, ParseException, InvalidTokenOffsetsException {
        // 目錄物件
        Directory directory = FSDirectory.open(new File("E://test"));
        // 建立讀取工具
        IndexReader reader = DirectoryReader.open(directory);
        // 建立搜尋工具
        IndexSearcher searcher = new IndexSearcher(reader);

        QueryParser parser = new QueryParser("content", new IKAnalyzer());
        Query query = parser.parse("大墓碑");

        // 格式化器
        Formatter formatter = new SimpleHTMLFormatter("<em>", "</em>");
        Scorer scorer = new QueryScorer(query);
        // 準備高亮工具
        Highlighter highlighter = new Highlighter(formatter, scorer);
        // 搜尋
        TopDocs topDocs = searcher.search(query, 10);
        System.out.println("本次搜尋共" + topDocs.totalHits + "條資料");

        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            // 獲取文件編號
            int docID = scoreDoc.doc;
            Document doc = reader.document(docID);
            System.out.println("id: " + doc.get("id"));

            String title = doc.get("content");
            // 用高亮工具處理普通的查詢結果,引數:分詞器,要高亮的欄位的名稱,高亮欄位的原始值
            String hTitle = highlighter.getBestFragment(new IKAnalyzer(), "content", title);

            System.out.println("title: " + hTitle);
            // 獲取文件的得分
            System.out.println("得分:" + scoreDoc.score);
        }
    }
}