Lucene輕量級搜索引擎,真的太強了!!!Solr 和 ES 都是基於它

来源:https://www.cnblogs.com/sun2020/p/18067127
-Advertisement-
Play Games

一、基礎知識 1、Lucene 是什麼 Lucene 是一個本地全文搜索引擎,Solr 和 ElasticSearch 都是基於 Lucene 的封裝 Lucene 適合那種輕量級的全文搜索,我就是伺服器資源不夠,如果上 ES 的話會很占用伺服器資源,所有就選擇了 Lucene 搜索引擎 2、倒排索 ...


一、基礎知識

1、Lucene 是什麼

Lucene 是一個本地全文搜索引擎,Solr 和 ElasticSearch 都是基於 Lucene 的封裝

Lucene 適合那種輕量級的全文搜索,我就是伺服器資源不夠,如果上 ES 的話會很占用伺服器資源,所有就選擇了 Lucene 搜索引擎

2、倒排索引原理

全文搜索的原理是使用了倒排索引,那麼什麼是倒排索引呢?

  1. 先通過中文分詞器,將文檔中包含的關鍵字全部提取出來,比如我愛中國,會通過分詞器分成我,愛,中國,然後分別對應‘我愛中國’
  2. 然後再將關鍵字與文檔的對應關係保存起來
  3. 最後對關鍵字本身做索引排序

3、與傳統資料庫對比

Lucene DB
資料庫表(table) 索引(index)
行(row) 文檔(document)
列(column) 欄位(field)

4、數據類型

常見的欄位類型

  1. StringField:這是一個不可分詞的字元串欄位類型,適用於精確匹配和排序
  2. TextField:這是一個可分詞的字元串欄位類型,適用於全文搜索和模糊匹配
  3. IntField、LongField、FloatField、DoubleField:這些是數值欄位類型,用於存儲整數和浮點數。
  4. DateField:這是一個日期欄位類型,用於存儲日期和時間。
  5. BinaryField:這是一個二進位欄位類型,用於存儲二進位數據,如圖片、文件等。
  6. StoredField:這是一個存儲欄位類型,用於存儲不需要被索引的原始數據,如文檔的內容或其他附加信息。

Lucene 分詞器是將文本內容分解成單獨的辭彙(term)的工具。Lucene 提供了多種分詞器,其中一些常見的包括

  1. StandardAnalyzer:這是 Lucene 預設的分詞器,它使用 UnicodeText 解析器將文本轉換為小寫字母,並且根據空格、標點符號和其他字元來進行分詞。
  2. CJKAnalyzer:這個分詞器專門為中日韓語言設計,它可以正確地處理中文、日文和韓文的分詞。
  3. KeywordAnalyzer:這是一個不分詞的分詞器,它將輸入的文本作為一個整體來處理,常用於處理精確匹配的情況。
  4. SimpleAnalyzer:這是一個非常簡單的分詞器,它僅僅按照非字母字元將文本分割成小寫辭彙。
  5. WhitespaceAnalyzer:這個分詞器根據空格將文本分割成小寫辭彙,不會進行任何其他的處理。

但是對於中文分詞器,我們一般常用第三方分詞器IKAnalyzer,需要引入它的POM文件

二、最佳實踐

1、依賴導入

<lucene.version>8.1.1</lucene.version>
<IKAnalyzer-lucene.version>8.0.0</IKAnalyzer-lucene.version>

<!--============lucene start================-->
<!-- Lucene核心庫 -->
<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-core</artifactId>
    <version>${lucene.version}</version>
</dependency>

<!-- Lucene的查詢解析器 -->
<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-queryparser</artifactId>
    <version>${lucene.version}</version>
</dependency>

<!-- Lucene的預設分詞器庫 -->
<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-analyzers-common</artifactId>
    <version>${lucene.version}</version>
</dependency>

<!-- Lucene的高亮顯示 -->
<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-highlighter</artifactId>
    <version>${lucene.version}</version>
</dependency>

<!-- ik分詞器 -->
<dependency>
    <groupId>com.jianggujin</groupId>
    <artifactId>IKAnalyzer-lucene</artifactId>
    <version>${IKAnalyzer-lucene.version}</version>
</dependency>
<!--============lucene end================-->

2、創建索引

  1. 先制定索引的基本數據,包括索引名稱和欄位
/**
 * @author: sunhhw
 * @date: 2023/12/25 17:39
 * @description: 定義文章文檔欄位和索引名稱
 */

public interface IArticleIndex {

    /**
     * 索引名稱
     */

    String INDEX_NAME = "article";

    // --------------------- 文檔欄位 ---------------------
    String COLUMN_ID = "id";
    String COLUMN_ARTICLE_NAME = "articleName";
    String COLUMN_COVER = "cover";
    String COLUMN_SUMMARY = "summary";
    String COLUMN_CONTENT = "content";
    String COLUMN_CREATE_TIME = "createTime";
}
  1. 創建索引並新增文檔
/**
 * 創建索引並設置數據
 *
 * @param indexName 索引地址
 */

public void addDocument(String indexName, List<Document> documentList) {
    // 配置索引的位置 例如:indexDir = /app/blog/index/article
    String indexDir = luceneProperties.getIndexDir() + File.separator + indexName;
    try {
        File file = new File(indexDir);
        // 若不存在,則創建目錄
        if (!file.exists()) {
            FileUtils.forceMkdir(file);
        }
        // 讀取索引目錄
        Directory directory = FSDirectory.open(Paths.get(indexDir));
        // 中文分析器
        Analyzer analyzer = new IKAnalyzer();
        // 索引寫出工具的配置對象
        IndexWriterConfig conf = new IndexWriterConfig(analyzer);
        // 創建索引
        IndexWriter indexWriter = new IndexWriter(directory, conf);
        long count = indexWriter.addDocuments(documentList);
        log.info("[批量添加索引庫]總數量:{}", documentList.size());
        // 提交記錄
        indexWriter.commit();
        // 關閉close
        indexWriter.close();
    } catch (Exception e) {
        log.error("[創建索引失敗]indexDir:{}", indexDir, e);
        throw new UtilsException("創建索引失敗", e);
    }
}
  1. 註意這裡有個坑,就是這個indexWriter.close();必須要關閉, 不然在執行其他操作的時候會有一個write.lock文件鎖控制導致操作失敗
  2. indexWriter.addDocuments(documentList)這是批量添加,單個添加可以使用indexWriter.addDocument()
  1. 單元測試
@Test
public void create_index_test() {
    ArticlePO articlePO = new ArticlePO();
    articlePO.setArticleName("git的基本使用" + i);
    articlePO.setContent("這裡是git的基本是用的內容" + i);
    articlePO.setSummary("測試摘要" + i);
    articlePO.setId(String.valueOf(i));
    articlePO.setCreateTime(LocalDateTime.now());
    Document document = buildDocument(articlePO);
    LuceneUtils.X.addDocument(IArticleIndex.INDEX_NAME, document);
}

private Document buildDocument(ArticlePO articlePO) {
    Document document = new Document();
    LocalDateTime createTime = articlePO.getCreateTime();
    String format = LocalDateTimeUtil.format(createTime, DateTimeFormatter.ISO_LOCAL_DATE);

    // 因為ID不需要分詞,使用StringField欄位
    document.add(new StringField(IArticleIndex.COLUMN_ID, articlePO.getId() == null ? "" : articlePO.getId(), Field.Store.YES));
    // 文章標題articleName需要搜索,所以要分詞保存
    document.add(new TextField(IArticleIndex.COLUMN_ARTICLE_NAME, articlePO.getArticleName() == null ? "" : articlePO.getArticleName(), Field.Store.YES));
    // 文章摘要summary需要搜索,所以要分詞保存
    document.add(new TextField(IArticleIndex.COLUMN_SUMMARY, articlePO.getSummary() == null ? "" : articlePO.getSummary(), Field.Store.YES));
     // 文章內容content需要搜索,所以要分詞保存
    document.add(new TextField(IArticleIndex.COLUMN_CONTENT, articlePO.getContent() == null ? "" : articlePO.getContent(), Field.Store.YES));
    // 文章封面不需要分詞,但是需要被搜索出來展示
    document.add(new StoredField(IArticleIndex.COLUMN_COVER, articlePO.getCover() == null ? "" : articlePO.getCover()));
    // 創建時間不需要分詞,僅需要展示
    document.add(new StringField(IArticleIndex.COLUMN_CREATE_TIME, format, Field.Store.YES));
    return document;
}

3、更新文檔

  1. 更新索引方法
/**
 * 更新文檔
 *
 * @param indexName 索引地址
 * @param document  文檔
 * @param condition 更新條件
 */

public void updateDocument(String indexName, Document document, Term condition) {
    String indexDir = luceneProperties.getIndexDir() + File.separator + indexName;
    try {
        // 讀取索引目錄
        Directory directory = FSDirectory.open(Paths.get(indexDir));
        // 中文分析器
        Analyzer analyzer = new IKAnalyzer();
        // 索引寫出工具的配置對象
        IndexWriterConfig conf = new IndexWriterConfig(analyzer);
        // 創建索引
        IndexWriter indexWriter = new IndexWriter(directory, conf);
        indexWriter.updateDocument(condition, document);
        indexWriter.commit();
        indexWriter.close();
    } catch (Exception e) {
        log.error("[更新文檔失敗]indexDir:{},document:{},condition:{}", indexDir, document, condition, e);
        throw new ServiceException();
    }
}
  1. 單元測試
@Test
public void update_document_test() {
    ArticlePO articlePO = new ArticlePO();
    articlePO.setArticleName("git的基本使用=編輯");
    articlePO.setContent("這裡是git的基本是用的內容=編輯");
    articlePO.setSummary("測試摘要=編輯");
    articlePO.setId("2");
    articlePO.setCreateTime(LocalDateTime.now());
    Document document = buildDocument(articlePO);
    LuceneUtils.X.updateDocument(IArticleIndex.INDEX_NAME, document, new Term("id""2"));
}
  1. 更新的時候,如果存在就更新那條記錄,如果不存在就會新增一條記錄
  2. new Term("id", "2")搜索條件,跟資料庫里的where id = 2差不多
  3. IArticleIndex.INDEX_NAME = article 索引名稱

4、刪除文檔

  1. 刪除文檔方法
/**
* 刪除文檔
*
@param indexName 索引名稱
@param condition 更新條件
*/

public void deleteDocument(String indexName, Term condition) {
  String indexDir = luceneProperties.getIndexDir() + File.separator + indexName;
  try {
      // 讀取索引目錄
      Directory directory = FSDirectory.open(Paths.get(indexDir));
      // 索引寫出工具的配置對象
      IndexWriterConfig conf = new IndexWriterConfig();
      // 創建索引
      IndexWriter indexWriter = new IndexWriter(directory, conf);

      indexWriter.deleteDocuments(condition);
      indexWriter.commit();
      indexWriter.close();
  } catch (Exception e) {
      log.error("[刪除文檔失敗]indexDir:{},condition:{}", indexDir, condition, e);
      throw new ServiceException();
  }
}
  1. 單元測試
@Test
public void delete_document_test() {
    LuceneUtils.X.deleteDocument(IArticleIndex.INDEX_NAME, new Term(IArticleIndex.COLUMN_ID, "1"));
}
  1. 刪除文檔跟編輯文檔類似

5、刪除索引

把改索引下的數據全部清空

/**
* 刪除索引
*
@param indexName 索引地址
*/

public void deleteIndex(String indexName) {
  String indexDir = luceneProperties.getIndexDir() + File.separator + indexName;
  try {
      // 讀取索引目錄
      Directory directory = FSDirectory.open(Paths.get(indexDir));
      // 索引寫出工具的配置對象
      IndexWriterConfig conf = new IndexWriterConfig();
      // 創建索引
      IndexWriter indexWriter = new IndexWriter(directory, conf);
      indexWriter.deleteAll();
      indexWriter.commit();
      indexWriter.close();
  } catch (Exception e) {
      log.error("[刪除索引失敗]indexDir:{}", indexDir, e);
      throw new ServiceException();
  }
}

6、普通查詢

  1. TermQuery查詢
	   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 當我們在引入應該組件的時候 提示找不到這個組件但是項目明明就有這個物理文件 報錯原因:typescript 只能理解 .ts 文件,無法理解 .vue文件 出現這樣的 第一種 方法就是在env.d.ts 裡面添加下麵代碼 1 declare module '*.vue' { 2 import typ ...
  • 這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 一、是什麼 Tree shaking 是一種通過清除多餘代碼方式來優化項目打包體積的技術,專業術語叫 Dead code elimination 簡單來講,就是在保持代碼運行結果不變的前提下,去除無用的代碼 如果把代碼打包比作製作蛋糕,傳 ...
  • 一、問題闡述 有的時候我們需要控制非同步函數的執行順序,比如a方法中如果要用到非同步函數b方法的請求結果,就需要進行順序控制,否則a函數先執行就會導致找不到數據直接報錯。 二、方法 1.非同步控制 1.1.async,await等做非同步控制 1.2修改函數放置位置達到非同步控制效果(我遇到的情況無效,但是確 ...
  • 網站: 即時熱點 - 正在發生的事 (Solo 社區投稿) 簡介: 一個熱門信息聚合站,幫助您輕鬆瞭解正在發生的事。 描述: 即時熱點是一個熱門信息聚合站,彙集來自百度、微博、頭條、知乎、抖音、快手等多個主流平臺的熱門話題,幫助您輕鬆瞭解正在發生的事。無需跳轉多個平臺,即刻瀏覽最新、最熱、最有趣的話 ...
  • 前言 我們每天寫的vue代碼都是寫在vue文件中,但是瀏覽器卻只認識html、css、js等文件類型。所以這個時候就需要一個工具將vue文件轉換為瀏覽器能夠認識的js文件,想必你第一時間就想到了webpack或者vite。但是webpack和vite本身是沒有能力處理vue文件的,其實實際背後生效的 ...
  • 過濾器和攔截器的辨析 介紹 過濾器和攔截器都是為了在請求到達目標處理器(Servlet或Controller)之前或者之後插入自定義的處理邏輯 過濾器: 遵循AOP(面向切麵編程)思想實現,基於Servlet規範提供的Filter介面,它是位於客戶端請求與伺服器響應之間的一個組件,依賴於Servle ...
  • 什麼是函數回調? 介紹 函數回調是一種編程概念,它描述的是這樣一個過程:一個函數(稱為回調函數)作為參數傳遞給另一個函數(稱為調用函數),當滿足一定條件或者在某個特定時刻,調用函數會調用傳遞過來的回調函數。這種機制允許程式員在編寫代碼時,能夠在不同的上下文中重用函數,同時也能實現非同步處理、事件驅動編 ...
  • 是的,\t 是指製表符(tab),它通常用作欄位分隔符在 TSV(Tab-Separated Values)格式的文件中。TSV是一種簡單的文本格式,它使用製表符來分隔每一列中的值,而每一行則代表一個數據記錄。 TSV文件例: ID\tName\tAge\tCity 1\tJohn Doe\t28\ ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...