首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

Lucene 搜索類實現:索引搜索與字符串匹配對比 (Java)

     編輯:關於C++

功能概述

實現一個搜索類 Search,提供兩種搜索方式:

  1. Lucene 索引搜索:利用 IndexSearcher、TermQuery 對已建立索引的文檔進行關鍵字查詢,輸出命中文檔名及頻次、耗時。
  2. 字符串逐行匹配:遍歷目錄下所有文件,用 String.indexOf 統計關鍵字出現次數,輸出結果與耗時。

核心代碼結構

public class Search {
    private String INDEX_STORE_PATH = "E:\\Lucene項目\\索引目錄";

    // Lucene 索引搜索
    public void indexSearch(String searchType, String searchKey) {
        IndexSearcher searcher = new IndexSearcher(INDEX_STORE_PATH);
        Term t = new Term(searchType, searchKey);
        Query q = new TermQuery(t);
        Date begin = new Date();
        TermDocs termDocs = searcher.getIndexReader().termDocs(t);
        while (termDocs.next()) {
            System.out.println("find " + termDocs.freq() + " matches in " +
                searcher.getIndexReader().document(termDocs.doc()).getField("fileName").stringValue());
        }
        Date end = new Date();
        System.out.println("索引搜索耗時: " + (end.getTime() - begin.getTime()) + "ms");
    }

    // 字符串匹配搜索
    public void stringSearch(String keyword, String searchDir) {
        File dir = new File(searchDir);
        File[] files = dir.listFiles();
        Map rs = new LinkedHashMap<>();
        Date begin = new Date();
        for (File f : files) {
            int hits = 0;
            String content = readFile(f); // 讀取全文
            int idx = -keyword.length();
            while ((idx = content.indexOf(keyword, idx + keyword.length())) != -1) hits++;
            rs.put(f.getName(), hits);
        }
        Date end = new Date();
        // 輸出結果與耗時...
    }

    public static void main(String[] args) {
        Search s = new Search();
        s.indexSearch("content", "保爾");
        s.stringSearch("保爾", "INDEX_STORE_PATH");
    }
}

關鍵點說明

  • Term 是 Lucene 搜索的最小單元(如詞語)。
  • TermDocs 提供文檔編號與詞頻的枚舉。
  • 字符串搜索需自行讀取文件內容,適合小規模數據對比驗證。
  • 主函數演示了對同一關鍵字「保爾」的兩種搜索方式對比。

依賴環境

需引入 Lucene 核心庫 (lucene-core.jar),JDK 1.8+。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved