type
status
date
slug
summary
tags
category
icon
password
MySQL 從 5.7.6 開始內建 ngrame 全文解析器,用來支援中文、日文、韓文分詞

InnoDB Full-Text Index

inverted index(倒排索引)

inverted index 經常被用於全文檢索,MySQL 的 Full-Text Index 也是基於 inverted index 來實現的。
inverted index 將文檔中的不重複單詞構成一個列表,每一個單詞都會記錄包含此單詞的文檔列表。

InnoDB Full-Text Index Tables

在建立 Full-Text Index 之後,還會出現以下 table:
可以分為 4 類-
  1. index_1~6:數量固定會有 6 個文件用於儲存倒排索引,儲存的是 words、position 和 DOC_ID,會根據 word 進行排序並分區映射到不同的文件中。 倒排索引分為 6 個表用來支持 parallel index creation,預設為 2 個線程,當在大表創建 Full-Text Index 時,可以透過 innodb_ft_sort_pll_degree 來調大併行線程數。
  1. deleted:包含資料已經刪除的 DOC_ID,但還沒從 Full-Text index 中刪除。 deleted_cache:為前者的內存緩存。
  1. being_deleted:包含資料已經刪除的 DOC_ID,且當前正在從 Full-Text index 中刪除。 being_deleted_cache:為前者的內存緩存。
  1. config:包含 Full-Text index 的內部狀態資訊,最重要的是其中有儲存 FTS_SYNCED_DOC_ID,該值用來記錄解析被寫到 disk 的 DOC_ID,在崩潰回覆時會根據這個值判斷哪些 DOC 需要重新解析並將其添加到 Full-text index cache,查詢 INFORMATION_SCHEMA.INNODB_FT_CONFIG 可以查看其中的資料。

InnoDB Full-Text Index Cache

InnoDB Full-Text Index DOC_ID and FTS_DOC_ID Column

InnoDB 需要透過 DOC_ID 來對應 Word 所在的紀錄,因此建立 Full-Text Index 的時候,也會在表上隱式建立一個 FTS_DOC_ID 的欄位,請參考以下事例:
因此在該表上建立第一個 Full-Text Index 需要重建表,如果想要避免重建表可以在 CREATE TABLE 時預先建立此欄位,如下事例:
刪除 Full-Text Index 時,為了避免下次建立時需重建表,因此不會移除 FTS_DOC_ID 欄位。

InnoDB Full-Text Index delete handling

為了避免 delete 原表資料時,在索引表中出現大量的 delete 引發資源爭用的問題,已刪除的 DOC_ID 會被記錄在 deleted 表中且不會在索引表中移出,而是會在返回查詢結果之前,透過 deleted 表來過濾已刪除的 DOC_ID。可以透過設置 innodb_optimize_fulltext_only = ON 後執行 OPTIMIZE TABLE 來重建 Full-Text Index 來移除已刪除 DOC_ID 的索引,這些會被轉存到 being_deleted 檔案中。

InnoDB Full-Text Index Transaction Handling

InnoDB Full-Text Indexes 相關 TABLE

information_schema 下有提供觀察 Full-Text Index 的表,在使用前須要先設定 innodb_ft_aux_table 調整為想要觀察的表,否則除了 INNODB_FT_DEFAULT_STOPWORD 以外都會是 empty。
共有以下 6 張表-
  • INNODB_FT_CONFIG:
  • INNODB_FT_INDEX_TABLE
  • INNODB_FT_INDEX_CACHE
  • INNODB_FT_DEFAULT_STOPWORD
  • INNODB_FT_DELETED
  • INNODB_FT_BEING_DELETED

全文檢索模式

IN NATURAL LANGUAGE MODE (自然語言模式)

此為默認的方式
 

IN Boolean

With Query Expansion (查詢擴展)

 
 

限制

有切 partition 的表不支援 FullText index
 

參考