<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Morton Kuo on Medium]]></title>
        <description><![CDATA[Stories by Morton Kuo on Medium]]></description>
        <link>https://medium.com/@mortonkuo?source=rss-7fb06f307fdd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gykFkqXG3KAOm8jz</url>
            <title>Stories by Morton Kuo on Medium</title>
            <link>https://medium.com/@mortonkuo?source=rss-7fb06f307fdd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:29:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mortonkuo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Elasticsearch 怎麼用？（四）]]></title>
            <link>https://medium.com/@mortonkuo/elasticsearch-%E6%80%8E%E9%BA%BC%E7%94%A8-%E5%9B%9B-3ec584a3aa74?source=rss-7fb06f307fdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ec584a3aa74</guid>
            <category><![CDATA[autocomplete]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Morton Kuo]]></dc:creator>
            <pubDate>Sun, 04 Dec 2022 14:29:22 GMT</pubDate>
            <atom:updated>2022-12-04T14:32:18.426Z</atom:updated>
            <content:encoded><![CDATA[<h4>實作自動完成？Prefix Query、Edge n-gram tokenizer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*baACUhN3A72imj4Z" /></figure><p><a href="https://medium.com/@mortonkuo/elasticsearch-%E6%80%8E%E9%BA%BC%E7%94%A8-%E4%BA%8C-9dec35c0b0d2">前幾篇文章</a>，已經簡單地瞭解了 Elasticsearch 的 text、keyword 型別，以及 term query、match query。開發者可以按自身需求，決定用什麼型別儲存資料、用什麼方式搜尋資料。</p><p>以圖書館搜尋藏書的功能為例，如果要查的是 ISBN，可以用 term query 搜尋 keyword 欄位，關鍵字全文比對原始資料。如果是要讓使用者關鍵字查詢書籍簡介，match query 全文搜尋 text 欄位能在一定程度上滿足需求。</p><p>不過現在的搜尋列只有上述功能可能還不太夠，更貼心者，應該使用者還沒打完關鍵字，搜尋列就要提供選項給使用者選擇。例如，書名搜尋「Ga」或「ga」就顯示「Game of Thrones」，也就是自動完成（Autocomplete）。這篇文章會整理兩個， 用 ES 提供實現自動完成的可能作法。</p><p>首先會遇到的問題是如何才搜得到該筆資料。快速建一個 books index，新增「Game of Thrones」、「Great Gatsby」，match query 用關鍵字「ga」搜尋 text 欄位的話，會發現查不到任何東西。這很正常，因為反向索引裡沒有「ga」這個 token。</p><pre>PUT /books<br><br>{<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;title&quot;: {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;fields&quot;: {<br>          &quot;raw&quot;: {<br>            &quot;type&quot;: &quot;keyword&quot;<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>要解決這個問題，想法有兩個</p><ol><li>前綴搜尋</li><li>把關鍵字加進反向索引</li></ol><p>第一點是搜尋時的解法，第二點是索引時的解法。對應到 ES ，前者可使用 Prefix Query，後者可用 Edge n-gram tokenizer。</p><p><strong>Prefix Query</strong></p><p>prefix query 是一種 term level query，意思是它跟 term query 一樣不對關鍵字進行文字分析，會用關鍵字全文查詢有無匹配。它使用起來相當容易，query 的類型明文 prefix 即可。</p><p>進一步而言，prefix query 會看反向索引是否用關鍵字當字首，是的話，就回傳該筆資料。而由於它預設 case sensitive，所以搜尋時要注意一下關鍵字、反向索引的大小寫。</p><p>以前例來說，prefix query 對 text 欄位搜尋「ga」，會回傳 2 筆資料：「Game of Thrones」、「Great Gatsby」。對 keyword 欄位搜尋「Ga」，會回傳 1 筆資料：「Game of Thrones」。</p><pre>GET books/_search<br><br>{ &quot;query&quot;: { &quot;prefix&quot;: { &quot;title&quot;: &quot;ga&quot; } } }<br><br>{ &quot;query&quot;: { &quot;prefix&quot;: { &quot;title.raw&quot;: &quot;Ga&quot; } } }</pre><p>這個作法，不用在製作索引時進行特別的設定，直接用 dynamic mapping，搜尋時 prefix query 下好關鍵字即可。</p><p><strong>Edge n-gram tokenizer</strong></p><p>第二個想法是把關鍵字加進反向索引。Autocomplete 的使用情境下，關鍵字是完整的搜尋條件的部分字元。上例來說，需要在使用者輸入「g」、「ga」、「gam」… 時回傳「Game of Thrones」供使用者選擇。</p><p>上述想法可透過 ES 提供的內建分詞器 Edge n-gram tokenizer來達成。它會從資料的起始字元開始用 x 個字元製作 token，直到 n 個字元的 token 製作完成。其中 x 預設是 1，n 預設為 2。</p><p>下面用測試分析器的 API 跟圖片來感受一下：</p><pre>POST /_analyze<br><br>{<br>  &quot;tokenizer&quot;: {<br>    &quot;type&quot;:&quot;edge_ngram&quot;<br>  },<br>  &quot;text&quot;: &quot;Game of Thrones&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nI_x2TrXgLEVChotSsfS9Q.png" /></figure><p>如果認為預設長度不符合需求，可以用 min_gram、max_gram 調整 x 及 n 的值。例如，如果認為 n 預設為 2 有點太短，不一定能篩選出使用者想要的關鍵字，可以把 n 設定成個案判斷適合的長度。例如下方維持 x，把 n 設定成 6，會得到下圖 6 個 token。</p><pre>{<br>  &quot;tokenizer&quot;: {<br>    &quot;type&quot;:&quot;edge_ngram&quot;,<br>    &quot;min_gram&quot;: 1,<br>    &quot;max_gram&quot;: 6<br>  },<br>  &quot;text&quot;: &quot;Game of Thrones&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4mH0dgpJol7W6SSSsWNcw.png" /></figure><p>這裡一併紀錄，除了 token 的字元數，Edge n-gram tokenizer 還可以在 token_chars<strong> </strong>指定 token 要納入哪種字元（預設接受所有字元）。如果資料包含不接受的字元，則會先以該字元進行分詞，再對各個分詞結果製作長度 x ~ n 的 token。</p><p>例如，下方設定只接受文字、不接受空格字元，x 為 1，n 為 2。則 Edge n-gram tokenizer 會先用空格分詞，分為「Game、of、thrones」，接著對上述三個分詞結果取 1 ~ 2 個字元當作 token。</p><pre>{<br>  &quot;tokenizer&quot;: {<br>    &quot;type&quot;:&quot;edge_ngram&quot;,<br>    &quot;min_gram&quot;: 2,<br>    &quot;max_gram&quot;: 4,<br>    &quot;token_chars&quot;: [<br>        &quot;letter&quot;<br>    ]<br>  },<br>  &quot;text&quot;: &quot;Game of thrones&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*59IGzw1TuwSczmwKbNA6hA.png" /></figure><p>這種分析方式在關鍵字的字詞可能不以固定順序排列時較有實益。例如說要找酷狗狗，可能輸入「Cool Dog」或「Dog Cool」，儲存資料時，就可以考慮使用上述方式。</p><p>由於我們要實現的是書名的自動完成，猜想使用者應該會按固定順序輸入關鍵字字詞，因此下面 token_chars 都先不進行設定，維持預設。</p><p>來實驗一下怎麼存資料、查資料。</p><p>為了要讓使用者輸入「ga」、「Ga」都能找到資料，我們要用 match query 把「ga」、「Ga」都標準化成「ga」來搜尋。不過 match query 使用的分析器要調整一下，因為在索引時會把可能被用來查詢的前綴都製作成反向索引，所以 match query 不需要進行分詞，只需要進行標準化。</p><p>換句話說，mapping 會設定：</p><ol><li>索引時分析器：使用 Edge n-gram tokenizer，標準化成小寫</li><li>搜尋時分析器：使用 keyword tokenizer 維持輸入全文，標準化成小寫</li></ol><pre>{<br>  &quot;settings&quot;: {<br>    &quot;analysis&quot;: {<br>      &quot;analyzer&quot;: {<br>        &quot;edge_ngram&quot;: {<br>          &quot;tokenizer&quot;: &quot;edge_ngram&quot;,<br>          &quot;filter&quot;: [<br>            &quot;lowercase&quot;<br>          ]<br>        },<br>        &quot;custom_search_analyzer&quot;: {<br>          &quot;tokenizer&quot;: &quot;keyword&quot;,<br>          &quot;filter&quot;: [<br>            &quot;lowercase&quot;<br>          ]<br>        }<br>      }<br>    }<br>  },<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;title&quot;: {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;analyzer&quot;: &quot;edge_ngram&quot;,<br>        &quot;search_analyzer&quot;: &quot;custom_search_analyzer&quot;<br>      }<br>    }<br>  }<br>}</pre><p>這樣就可以成功用 Edge n-gram tokenizer、match query 實現自動完成了。</p><pre>{ &quot;query&quot;: { &quot;match&quot;: { &quot;title&quot;: &quot;Ga&quot; } } }<br><br>{ &quot;query&quot;: { &quot;match&quot;: { &quot;title&quot;: &quot;ga&quot; } } }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*2gIn0NJ3yBlv86L0n__mAw.png" /></figure><p><strong>整理</strong></p><ol><li>透過 ES 實作自動完成，有兩個方向：搜尋時解法、索引時解法。</li><li>Prefix Query 是搜尋時解法，要留意搜尋時關鍵字大小寫的處理 。</li><li>Edge n-gram tokenizer 是索引時解法，會按設定把前綴製作成反向索引</li><li>使用 Edge n-gram tokenizer 的話，搜尋時不須分詞，標準化成小寫即可</li></ol><p><strong>參考資料</strong></p><ol><li><a href="https://opster.com/guides/elasticsearch/how-tos/elasticsearch-auto-complete-guide/">Elasticsearch Autocomplete Guide</a></li><li><a href="https://realpandablog.wordpress.com/2019/09/11/search-as-you-type-n-grams-suggesters-in-elasticsearch/">Search-as-you-type, N-grams &amp; Suggesters in Elasticsearch</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/8.5/query-dsl-prefix-query.html#query-dsl-prefix-query">Prefix Query</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-edgengram-tokenizer.html#analysis-edgengram-tokenizer">Edge n-gram tokenizer</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ec584a3aa74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elasticsearch 怎麼用？（三）]]></title>
            <link>https://medium.com/@mortonkuo/elasticsearch-%E6%80%8E%E9%BA%BC%E7%94%A8-%E4%B8%89-3c29db8d9451?source=rss-7fb06f307fdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c29db8d9451</guid>
            <category><![CDATA[bm25]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[similarity]]></category>
            <category><![CDATA[full-text-search]]></category>
            <dc:creator><![CDATA[Morton Kuo]]></dc:creator>
            <pubDate>Sat, 26 Nov 2022 13:07:24 GMT</pubDate>
            <atom:updated>2022-11-26T16:03:07.089Z</atom:updated>
            <content:encoded><![CDATA[<h4>相關度的加減乘除：TF-IDF、BM25</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_wXPgWPcyLmMMkJe" /></figure><p><a href="https://medium.com/@mortonkuo/elasticsearch-%E6%80%8E%E9%BA%BC%E7%94%A8-%E4%BA%8C-9dec35c0b0d2">前一篇文章</a>有提到，Elasticsearch 的 match query 是一種全文檢索，會對查詢的關鍵字進行文字分析，用 tokens 比對反向索引，回傳匹配資料。這裡要進一步問的是，那要怎麼知道每筆回傳資料跟關鍵字有多相關呢？這涉及的是相關度分數（Relevance / Similaraty / Scoring）的計算。</p><p>在 ES 中，如果開發者沒有透過 explicit mapping 設定 index 或欄位層級的計算方式（可設定成 ES 內建的其他選項或自定義），則預設的相關度演算法會是 BM25（Best Matching 25）。</p><p>而所謂 BM25 是 TF-IDF 演算法的變體。在 ES 的較早版本中，預設的相關度演算法是 TF-IDF。但現行版本，TF-IDF 已改稱為 Classic，只能透過自定義來復刻。由於 BM25 是基於 TF-IDF 進行調整，基本想法上相近，所以下面主要整理、測試相對單純的 TF-IDF。</p><p><strong>TF-IDF</strong></p><p>TF-IDF 由三個相當直覺的指標組成：</p><ol><li>詞頻（Term Frequency）</li><li>逆向文件頻率（Inverse Document Frequency）</li><li>欄位長度（Field Length Norm）</li></ol><p>詞頻，指 token 在文件的指定欄位中出現的次數，詞頻越高，相關度越高。逆向文件頻率，指 token 在所有文件的指定欄位中出現的次數，可以把它理解成 token 的稀有度，token 出現在所有文件的頻率越低，相關度越高。欄位長度，則看實際資料的總長，長度越短，相關度越高。</p><p>計算式可參考官方文件復刻 TF-IDF 的 Script（省略型別跟部分參數）：</p><pre>tf = Math.sqrt(doc.freq);<br>idf = Math.log((field.docCount + 1)/(term.docFreq + 1)) + 1;<br>norm = 1/Math.sqrt(doc.length);<br><br>return tf * idf * norm;</pre><ul><li>doc.freq = 目前的 token 在目前文件的指定欄位中出現的次數</li><li>field.docCount = 指定欄位有值的文件數量</li><li>term.docFreq = 指定欄位有目前的 token 的文件數量</li><li>doc.length = 目前文件的指定欄位的 tokens 總數</li></ul><p>這裡要注意 Math.log 的基數約等於 2.7182818（e），後續手動計算驗證才會對得起來。認識了三個指標如何計算，可以來計算文件的相關度了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDz6LKYUwAiRyiPP2vM_vg.png" /></figure><p>ES 會對每個匹配的 token，計算它在當前文件中，三個指標各是多少。接著把三個指標相乘，得出當前 token 對當前文件的相關度。最後將每個 token 對當前文件的相關度進行加總，加總結果就是當前文件的相關度。</p><p>動手觀察看看。這裡建一個 greeting index，把相關度的計算方式設定成 TF-IDF。接著，新增 2 筆資料「Hello, adventurer!」（資料 A）及「Hello, world!」（資料 B）。 match query 搜尋關鍵字「Hello, adventurer!」，參數加上 explain 來確認計算。</p><pre>PUT /greeting<br><br>{<br>  &quot;settings&quot;: {<br>    &quot;similarity&quot;: {<br>      &quot;tfidf&quot;: {<br>        &quot;type&quot;: &quot;scripted&quot;,<br>        &quot;script&quot;: {<br>          &quot;source&quot;: &quot;double tf = Math.sqrt(doc.freq); double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; double norm = 1/Math.sqrt(doc.length); return query.boost * tf * idf * norm;&quot;<br>        }<br>      }<br>    }<br>  },<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;message&quot;: {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;similarity&quot;: &quot;tfidf&quot;<br>      }<br>    }<br>  }<br>}</pre><pre>POST /greeting/_doc<br><br>{ &quot;message&quot;: &quot;Hello, world!&quot; }<br>{ &quot;message&quot;: &quot;Hello, adventurer!&quot; }</pre><pre>GET /greeting/_search<br><br>{<br>    &quot;explain&quot;: true,<br>    &quot;query&quot;: {<br>        &quot;match&quot;: {<br>            &quot;message&quot;:{<br>                &quot;query&quot;:&quot;Hello, adventurer!&quot;<br>            } <br>        }<br>    }<br>}</pre><p>搜尋結果會回傳 A、B 兩筆資料。這是因為關鍵字「Hello, adventurer!」被切割成「hello、adventurer」，從「hello」的反向索引來看，它在 A、B 兩筆資料中都有出現。相關度分數，A 是 1.7009207，B 是 0.70710677（下面省略無關計算的部分）。</p><pre>{<br>  &quot;hits&quot;: [<br>    {<br>      &quot;_source&quot;: {<br>        &quot;message&quot;: &quot;Hello, adventurer!&quot;<br>      },<br>      &quot;_explanation&quot;: {<br>        &quot;value&quot;: 1.7009207,<br>        &quot;description&quot;: &quot;sum of:&quot;,<br>        &quot;details&quot;: [<br>          {<br>            &quot;description&quot;: &quot;weight(message:hello in 0) [PerFieldSimilarity], result of:&quot;,<br>            &quot;details&quot;: [<br>              {<br>                &quot;value&quot;: 0.70710677,<br>                &quot;details&quot;: [<br>                  {<br>                    &quot;value&quot;: 2,<br>                    &quot;description&quot;: &quot;field.docCount&quot;<br>                  },<br>                  {<br>                    &quot;value&quot;: 2,<br>                    &quot;description&quot;: &quot;term.docFreq&quot;<br>                  },<br>                  {<br>                    &quot;value&quot;: 1.0,<br>                    &quot;description&quot;: &quot;doc.freq&quot;<br>                  },<br>                  {<br>                    &quot;value&quot;: 2,<br>                    &quot;description&quot;: &quot;doc.length&quot;<br>                  }<br>                ]<br>              }<br>            ]<br>          },<br>          {<br>            &quot;description&quot;: &quot;weight(message:adventurer in 0) [PerFieldSimilarity], result of:&quot;,<br>            &quot;details&quot;: [<br>              {<br>                &quot;value&quot;: 0.99381393,<br>                &quot;details&quot;: [<br>                  {<br>                    &quot;value&quot;: 2,<br>                    &quot;description&quot;: &quot;field.docCount&quot;<br>                  },<br>                  {<br>                    &quot;value&quot;: 1,<br>                    &quot;description&quot;: &quot;term.docFreq&quot;<br>                  },<br>                  {<br>                    &quot;value&quot;: 1.0,<br>                    &quot;description&quot;: &quot;doc.freq&quot;<br>                  },<br>                  {<br>                    &quot;value&quot;: 2,<br>                    &quot;description&quot;: &quot;doc.length&quot;<br>                  }<br>                ]<br>              }<br>            ]<br>          }<br>        ]<br>      }<br>    },<br>    {<br>      &quot;_source&quot;: {<br>        &quot;message&quot;: &quot;Hello, world!&quot;<br>      },<br>      &quot;_explanation&quot;: {<br>        &quot;value&quot;: 0.70710677,<br>        &quot;description&quot;: &quot;sum of:&quot;,<br>        &quot;details&quot;: [<br>          {<br>            &quot;description&quot;: &quot;weight(message:hello in 0) [PerFieldSimilarity], result of:&quot;,<br>            &quot;details&quot;: [<br>              {<br>                &quot;value&quot;: 0.70710677,<br>                &quot;details&quot;: [<br>                  {<br>                    &quot;value&quot;: 2,<br>                    &quot;description&quot;: &quot;field.docCount&quot;<br>                  },<br>                  {<br>                    &quot;value&quot;: 2,<br>                    &quot;description&quot;: &quot;term.docFreq&quot;<br>                  },<br>                  {<br>                    &quot;value&quot;: 1.0,<br>                    &quot;description&quot;: &quot;doc.freq&quot;<br>                  },<br>                  {<br>                    &quot;value&quot;: 2,<br>                    &quot;description&quot;: &quot;doc.length&quot;<br>                  }<br>                ]<br>              }<br>            ]<br>          }<br>        ]<br>      }<br>    }<br>  ]<br>}</pre><p>可以注意到：</p><ol><li>「hello」在 A、B 中分數相同，因為詞頻、稀有度、欄位長度都相同</li><li>「adventurer」分數比「hello」高，因為它比較稀有，只 A 有該 token</li><li>A 總分高於 B，因為 A 匹配 2 個 token，B 只匹配 1 個</li></ol><p>新增第 3 筆資料「Hello. Hello.」（資料 C）查一樣的關鍵字，則：</p><ol><li>A 的相關度會變高，從 1.7009207 上升到 1.9043427。這部分貢獻來自「adventurer」，它變得更稀有了（field.docCount 從 2 上升到 3）。</li><li>「hello」在 C 的分數會比 A、B 高，因為詞頻較高（doc.freq = 2）。</li></ol><p>新增第 4 筆資料「Hello, Lorem ipsum dolor sit amet, consectetur!」（資料 D）繼續查，「hello」在 D 的分數會較低，只有 0.37796447，A、B、C 維持前次分數。原因是 D 的欄位長度比 A、B、C 長，稀釋了 token 的重要性。</p><p><strong>BM25</strong></p><p>那 BM25 怎麼算？用 explain 確認計算式如下（省略部分參數）。可以發現除了使用詞頻、逆向文件頻率及欄位長度，還會加上用來調整詞頻、欄位長度對分數的影響的參數。</p><pre>tf = freq / (freq + k1 * (1 - b + b * dl / avgdl))<br>idf = log(1 + (N - n + 0.5) / (n + 0.5))<br><br>return idf * tf</pre><ul><li>freq = 目前的 token 在目前文件的指定欄位中出現的次數</li><li>N = 指定欄位有值的文件數量</li><li>n = 指定欄位有目前的 token 的文件數量</li><li>dl = 欄位長度</li><li>avgdl = 欄位平均長度</li><li>k1 = 調整詞頻對分數的影響的參數，預設 1.2</li><li>b = 調整欄位長度對分數的影響的參數，預設 0.75</li></ul><p>基本想法跟 TF-IDF 是一樣的，token 出現次數（freq）越多，詞頻越高，相關度越高。token 出現在其他文件的次數（n）越低，逆向文件頻率越低，相關度越高。欄位實際長度越短（dl），相關度越高。</p><p>新增的兩個參數。k1 的部分，可以決定 token 每多出現 1 次是都加 1 分，還是加的分數要遞減，例如第 1 次加 0.5、第 2 次加 0.4、第 3 次加 0.3。b 的部份，可代入 0 ，會發現欄位長度對分數的影響會被直接消除。</p><p>同樣地，特定文件的相關度，就是該文件匹配 tokens 的相關度總和。</p><p><strong>整理</strong></p><ol><li>全文檢索須決定相關度如何計算</li><li>ES 預設的相關度演算法是 BM25，它是 TF-IDF 的變化版</li><li>TF-IDF、BM25 都用詞頻、逆向文件頻率、欄位長度計算 token 相關度</li><li>特定文件的相關度，就是該文件匹配 tokens 的相關度總和</li><li>BM25 可用額外參數調整詞頻、欄位長度對相關度的影響</li></ol><p><strong>參考資料</strong></p><ol><li><a href="https://levelup.gitconnected.com/the-beginners-guide-to-search-relevance-with-elasticsearch-e7ee61f0695f">The Beginners Guide to Search Relevance with Elasticsearch</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/8.5/similarity.html#similarity">Similarity</a>、<a href="https://www.elastic.co/guide/en/elasticsearch/reference/8.5/index-modules-similarity.html#index-modules-similarity">Similarity Module</a>、<a href="https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-similarity-context.html#painless-similarity-context">Similarity Context</a></li><li><a href="https://codeburst.io/deconstructing-scoring-in-elasticsearch-e8544676a24">Deconstructing Scoring In Elasticsearch</a></li><li><a href="https://www.elastic.co/blog/practical-bm25-part-2-the-bm25-algorithm-and-its-variables">Practical BM25 — Part 2: The BM25 Algorithm and its Variables</a></li><li><a href="https://opensourceconnections.com/blog/2015/10/16/bm25-the-next-generation-of-lucene-relevation/">BM25 The Next Generation of Lucene Relevance</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c29db8d9451" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elasticsearch 怎麼用？（二）]]></title>
            <link>https://medium.com/@mortonkuo/elasticsearch-%E6%80%8E%E9%BA%BC%E7%94%A8-%E4%BA%8C-9dec35c0b0d2?source=rss-7fb06f307fdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dec35c0b0d2</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[mapping]]></category>
            <category><![CDATA[analyzer]]></category>
            <category><![CDATA[query]]></category>
            <dc:creator><![CDATA[Morton Kuo]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 16:54:05 GMT</pubDate>
            <atom:updated>2022-11-26T16:03:45.167Z</atom:updated>
            <content:encoded><![CDATA[<h4>資料儲存及查詢的基本操作：分析器、型別、 Query</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YOQhVhMhyDERCjXM" /></figure><p>我們成功地在<a href="https://medium.com/@mortonkuo/%E4%BB%80%E9%BA%BC%E6%98%AF-elasticsearch-2af2304aed0b">前一篇文章</a>中建立了一個 Elasticsearch 的節點，想要開始存資料、查資料了。不過 ES 的用語要先熟悉一下：Index、Document、Field、Mapping 。跟 MySQL 的用語類比一下。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*U-3e_SPvFl_o-WHmzWn17A.png" /></figure><p><strong>Schema-less、Dynamic mapping</strong></p><p>瞭解用語以後，從 schema 開始看。有別於 MySQL 儲存資料前要事先定義 schema，且資料必須符合定義，才能存進表裡，ES 採取 Schema-less 的設計。所謂 Schema-less 是指不須事先定義 mapping，ES 會在存資料時自動新增 index，且會偵測資料的各個欄位，把對應型別加進 mapping。</p><p>這功能也稱為 dynamic mapping，相對的是 explicit mapping，即開發者自己新增 index，並自訂 mapping。雖然前者使用起來比較方便，利於快速上手，但後續會看到，ES 有些功能要用後者設定。</p><p>現在來存一筆資料，觀察一下 dynamic mapping。怎麼存？ES 提供 REST API 讓使用者透過 curl、Postman 等方式送出 HTTP 請求操作資料。Kibana 也提供了開發者工具讓使用者進行操作。這裡我們送出下列請求，存一筆資料看看，request body 用JSON 帶上要存的資料。</p><pre># POST<br>https://localhost:9200/books/_doc</pre><pre>{ &quot;title&quot;: &quot;earthsea&quot; }</pre><p>查一下 books index 存不存在。可以看到 books 有自動建立起來了，且能在其中查到「earthsea」這筆資料。</p><pre># GET<br>https://localhost:9200/books/_search</pre><pre>{ &quot;query&quot;: { &quot;match_all&quot;: {} }}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*KipQiVHu9Bg5pvtB3UFHBQ.png" /></figure><p>那 books 的 mapping 長什麼樣子呢？</p><pre># GET<br>https://localhost:9200/books/_mapping</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*Ukkdgt7YWo0HTcBIpJLkeQ.png" /></figure><p>這裡可以看到，針對 title 欄位，ES 新增了兩個型別：text、keyword。待會再來看這兩者的差異，我們接著存一筆包含了整數、非整數、日期的資料。再檢查一次，會發現現在 mapping 從原本只有 1 個欄位變成 4 個欄位，新增欄位的型別分別是 long、float 及 date。</p><pre>{<br>    &quot;title&quot;: &quot;the da vinci code&quot;,<br>    &quot;stock&quot;: 5,<br>    &quot;price&quot;: 12.99,<br>    &quot;published&quot;: &quot;2003/03/18&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*iXcKPtUIpbe38r4Xv-l0Ig.png" /></figure><p>以上就實際觀察到 Schema-less、Dynamic mapping 了：ES 可以在存資料時自行偵測、設定欄位型別。</p><p><strong>型別、反向索引</strong></p><p>按照預設，ES 會幫每筆資料的所有欄位製作索引，文字類型的欄位（text field），其索引方式就會是用來加速全文檢索的反向索引。接著 ES 會把資料全部存進 _source。查詢資料發現有匹配文件時，就會回傳 _source。</p><p>回頭看前面 ES 幫我們新增的兩個型別keyword、text，它們就是文字類型的欄位，會被製作成反向索引。兩者的差異是，前者的反向索引是欄位全文，後者則會對全文進行文字分析（text analysis），把全文按指定方式拆成一個個字詞（token）後，才用各字詞製作反向索引。</p><p><strong>分析器</strong></p><p>文字分析會由分析器（Analyzer）來執行。分析器由一個必要元件跟兩組非必要元件組成：Character filter、Tokenizer、Token filter。其中 Tokenizer 是必要且唯一的，另外兩者則非必要元件，但想要的話可以裝很多個。三個元件會依序執行，功能大致如下，最後才生產出索引。</p><ul><li>Character filter：替換、刪除特定字元</li><li>Tokenizer：依特定規則進行分詞</li><li>Token filter：刪除指定字詞（停用詞）、標準化（大小寫轉換）</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3IZaFpYcu2HHSVaVcb09Q.png" /></figure><p>ES 提供了很多內建分析器、元件供開發者選擇，開發者可以用內建選項組裝符合自身需求的分析器。如果不敷使用，也可以另外安裝 <a href="https://www.elastic.co/guide/en/elasticsearch/plugins/current/analysis.html#analysis">plugin</a>。</p><p>下面手作一個符合上圖的分析器，用測試分析器的 API 測試一下。</p><pre># POST<br>https://localhost:9200/_analyze</pre><pre>{<br>    &quot;char_filter&quot;: [&quot;html_strip&quot;],<br>    &quot;tokenizer&quot;: &quot;standard&quot;,<br>    &quot;filter&quot;: [&quot;lowercase&quot;],<br>    &quot;text&quot;: &quot;&lt;b&gt;Welcome&lt;/b&gt; Aboard&quot;<br>}</pre><p>這裡 Character filter 用了清除 HTML tag 的 HTML strip 過濾器。Tokenizer 保留了預設分析器 standard analyzer 使用的 standard tokenizer，可理解成它會按空格切分字詞並去除標點符號。最後，Token filter 加上把 token 標準化成小寫的 lowercase 過濾器。</p><p>測試資料是「&lt;b&gt;Welcome&lt;/b&gt; Aboard」，可以看到產出的 tokens 確實是「welcome、aboard」。表示存資料時，如果使用了這個自訂分析器，反向索引的值就是這兩個字。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*ZkM77hRDmtXFXoS0EKvdJg.png" /></figure><p>不過要怎麼設定存資料用什分析器？就用上面說的 explicit mapping。手動新增一個名為 greeting 的 index，在 settings 定義自訂的分析器，然後在 message 欄位設定使用該分析器。</p><pre># PUT<br>https://localhost:9200/greeting</pre><pre>{<br>    &quot;settings&quot;: {<br>        &quot;analysis&quot;: {<br>            &quot;analyzer&quot;: {<br>                &quot;greeting_analyzer&quot;: {<br>                    &quot;type&quot;: &quot;custom&quot;,<br>                    &quot;char_filter&quot;: [&quot;html_strip&quot;],<br>                    &quot;tokenizer&quot;: &quot;standard&quot;,<br>                    &quot;filter&quot;: [&quot;lowercase&quot;]<br>                }<br>            }<br>        }<br>    },<br>    &quot;mappings&quot;: {<br>        &quot;properties&quot;: {<br>            &quot;message&quot;: {<br>                &quot;type&quot;: &quot;text&quot;,<br>                &quot;analyzer&quot;: &quot;greeting_analyzer&quot;<br>                &quot;fields&quot;:{<br>                    &quot;raw&quot;:{<br>                        &quot;type&quot;: &quot;keyword&quot;<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>Term Query、Match Query</strong></p><p>接著看怎麼查資料。要先認識的是 term query、match query<strong>。</strong>前者相對單純，執行時，直接用關鍵字看反向索引裡有沒有匹配的字詞，匹配的，就回傳原始資料。後者則比較有趣，它是一種全文檢索，會對關鍵字進行文字分析，再查詢有沒有匹配的資料。換句話說，文字分析會發生在兩個時點：</p><ol><li>存 text 型別資料，製作索引時（index time）</li><li>用 match query 查資料時（search time）</li></ol><p>那 match query 用什麼分析器？ 簡化地說，自訂 mapping 時，除了可以設定索引分析器，也可以設定查詢分析器。如果不設定查詢分析器，則 match query 會用索引分析器來進行文字分析（詳細<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/specify-analyzer.html#specify-search-analyzer">這裡</a>）。</p><p>下面觀察一下上述兩種資料型別，搭配兩種查詢，各組回傳結果是什麼。測試資料是「Welcome Aboard」，我們把它存進 greeting index。查詢關鍵字是「Welcome Aboard」（大寫）及「welcome aboard」（小寫）。</p><pre># Term + Keyword<br>{ &quot;query&quot;: { &quot;term&quot;: { &quot;message.raw&quot;: &quot;Welcome Aboard&quot; } } }<br>{ &quot;query&quot;: { &quot;term&quot;: { &quot;message.raw&quot;: &quot;welcome aboard&quot; } } }<br><br># Term + Text<br>{ &quot;query&quot;: { &quot;term&quot;: { &quot;message&quot;: &quot;Welcome Aboard&quot; } } }<br>{ &quot;query&quot;: { &quot;term&quot;: { &quot;message&quot;: &quot;welcome aboard&quot; } } }<br><br># Match + Keyword<br>{ &quot;query&quot;: { &quot;match&quot;: { &quot;message.raw&quot;: &quot;Welcome Aboard&quot; } } }<br>{ &quot;query&quot;: { &quot;match&quot;: { &quot;message.raw&quot;: &quot;welcome aboard&quot; } } }<br><br># Match + Text<br>{ &quot;query&quot;: { &quot;match&quot;: { &quot;message&quot;: &quot;Welcome Aboard&quot; } } }<br>{ &quot;query&quot;: { &quot;match&quot;: { &quot;message&quot;: &quot;welcome aboard&quot; } } }</pre><p>查詢結果整理如下，O 表示有查到資料，X 表示沒有查到。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*2yuwV0CZBC7q5ph327RMtw.png" /></figure><p>第 1 組，因為 term query 給什麼就查什麼，且 keyword 型別存了完整的「Welcome Aboard」，所以大寫查得到資料，小寫查不到資料。</p><p>第 2 組，text 型別存「welcome、aboard」這兩個 tokens，term query 用整句去查，當然就都查不到。必須關鍵字用 welcome 或 aboard 才查得到。</p><p>第 3 組讓人比較意外，大寫竟然有回傳資料。原本想法是這樣： keyword 型別不進行文字分析，所以 match query 可能用預設的 standard analyzer，把「Welcome Aboard」切成「welcome、aboard」查詢，而反向索引存完整的「Welcome Aboard」，應該沒有匹配。</p><p>把 match query 的分析器在查詢時明文指定成 standard analyzer 測看看。確實沒有匹配資料。這表示 match query 查 keyword 型別，且不指定分析器時，使用的分析器不是 standard analyzer。</p><pre>{<br>    &quot;query&quot;: {<br>        &quot;match&quot;: {<br>            &quot;message.raw&quot;:{<br>                &quot;query&quot;:&quot;Welcome Aboard&quot;,<br>                &quot;analyzer&quot;: &quot;standard&quot;<br>            } <br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*jtfnfS4_QvYbWkiJ2bbV0Q.png" /></figure><p>目前找到的一種解釋是， keyword 型別的分析器是 term analyzer，它不切分語句，所以 match query 文字分析後會維持原文，因此可找到匹配的資料。這部分實際如何運作有待釐清。但無論如何，第 3 種組合是查得到資料的。</p><p>第 4 組，因為 token filter 會把 tokens 轉換成小寫，所以不論是用大寫關鍵字或小寫關鍵字查詢，都會跟反向索引的內容匹配。</p><p><strong>整理</strong></p><ol><li>ES 採 Schema-less 的設計，新增資料會自動建立 index、設定欄位型別</li><li>文字欄位（keyword、text 型別）會製作反向索引，資料存在 _source</li><li>text 型別的反向索引是 tokens，keyword 型別則是全文</li><li>手動新增 index 時，可以指定 text 型別的索引時、查詢時分析器</li><li>match query 用 tokens 查有無匹配，term query 則用全文來查</li><li>match query 查 keyword 型別，可查到跟關鍵字完全一致的資料</li></ol><p><strong>參考資料</strong></p><ol><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/documents-indices.html#documents-indices">Data in: documents and indices</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html#mapping-types">Field Data Types</a></li><li><a href="https://codecurated.com/blog/elasticsearch-text-vs-keyword/">Elasticsearch: Text vs. Keyword</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/8.5/mapping-store.html">Store</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/8.5/mapping-source-field.html">Source Field</a></li><li><a href="https://stackoverflow.com/questions/67155998/how-to-index-a-field-in-elasticsearch-but-not-store-it-in-source">How to index a field in elasticsearch but not store it in _source</a></li><li><a href="https://stackoverflow.com/questions/28678296/elasticsearch-store-field-vs-source">Elasticsearch store field vs _source</a></li><li><a href="https://betterprogramming.pub/an-introduction-to-analyzers-in-elasticsearch-9596917693a2">An Introduction to Analyzers in Elasticsearch</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dec35c0b0d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[資料庫的索引是什麼？]]></title>
            <link>https://medium.com/@mortonkuo/%E8%B3%87%E6%96%99%E5%BA%AB%E7%9A%84%E7%B4%A2%E5%BC%95%E6%98%AF%E4%BB%80%E9%BA%BC-1824d7c79782?source=rss-7fb06f307fdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1824d7c79782</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[index]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[inverted-index]]></category>
            <dc:creator><![CDATA[Morton Kuo]]></dc:creator>
            <pubDate>Tue, 15 Nov 2022 08:05:58 GMT</pubDate>
            <atom:updated>2022-11-17T16:15:56.873Z</atom:updated>
            <content:encoded><![CDATA[<p>簡介索引的基本概念：好處及壞處、正向及反向索引</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FMUnStG23X9F_BRd" /></figure><p>資料的儲存方式會影響查找資料的效率，幫資料加上索引（index），可以加速資料查找。想像現在在一間圖書館裡，要找某本書，先當成冰與火之歌好了，按照圖書館擺放書籍的方式，我們會有完全不同的搜尋體驗：</p><ol><li>書完全隨意放，沒有任何索引</li><li>按書名的字首排序，從書名就可看出書在哪一區書櫃</li></ol><p>第一種方式，我們只能努力地從第一排走到最後一排書架，逐本檢查有沒有我們要找的書（Full Table Scan）。第二種方式則顯然能讓我們比較快地找到冰與火之歌，只需要看書名都以冰字作開頭的書架就好了。</p><p>資料庫也一樣，要加速資料查找的效率，一種可行的方式就是幫資料加上索引。例如，在 MySQL 輸入下列指令 ，就會用 title 欄位新增一組索引。之後用書名當關鍵字搜尋時，就能較快地找到對應資料。</p><pre>CREATE INDEX title_index ON books (title);</pre><p><strong>好處、壞處及注意事項</strong></p><p>資料跟索引的關係，先簡化想成這樣：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LJHzsDG8JFMZuqIfbRBig.png" /></figure><p>透過圖片可以發現幾件事。首先，新增索引會額外紀錄指定欄位每筆資料的原始位置。所以它會耗費磁碟空間，是用「空間換取時間」。</p><p>而上面例子之所以能比較快地找到資料，是因為書名按字首排序。如果不按字首排序（除排序外，也可能使用雜湊），使用索引就還是得逐列比對。這點來說，MySQL 預設的儲存引擎 InnoDB，會用 B+ Tree 來儲存索引，而 B+ Tree 就是一種有序的資料結構，可二元搜尋（Binary Search）加速查找。</p><p>不過這也意味著，相較於沒有使用索引時，新增資料只須在表格上新增一列就執行完畢，使用索引，增、刪、修改資料會要執行額外的操作來維持索引的排序。換句話說，是用更新效能換取查找效能。</p><p>因此，如果特定欄位會頻繁更新，就較不適合設定成索引。而每個索引都有自己的結構要維護，把多少個欄位設定成索引，增、刪資料時就要維護多少個索引，所以索引越多，增、刪資料執行成本就會越高。相反地，如果資料不常更新，或有少數欄位常被用來當成搜尋條件，就可考慮把這些欄位設定成索引，以提升查找效能。</p><p>此外，索引要建立在內容差異較大的欄位上。如果欄位內容不是 A 就是 B，A、B 分佈上各佔一半，可能被查詢優化器判斷成不如全表掃描。</p><p>實際測試一下。用 MySQL 新增 books 表，加入 10 萬筆測試資料，title、author、summary 都由隨機字串組成，字數分別介於 20 ~ 100、10 ~ 30、300 ~ 500 之間。最後一筆資料的書名設定成冰與火之歌。</p><pre>CREATE TABLE books (<br>  id INT UNSIGNED NOT NULL AUTO_INCREMENT,<br>  title VARCHAR(100) NOT NULL,<br>  author VARCHAR(30) NOT NULL,<br>  summary VARCHAR(500) NOT NULL,<br>  PRIMARY KEY(id)<br>);</pre><pre>const sql = &#39;INSERT INTO books (title, author, summary) VALUES ?&#39;;<br><br>promisePool.query(sql, genBook(100000));</pre><ul><li>無索引</li></ul><p>搜尋時間約 0.03 秒。回過頭來用 explain 觀察搜尋指令是怎麼執行的，可以看到 key 是 NULL， rows 是 96246，意思是不會使用任何索引，MySQL 預估要檢視 96246 筆資料，才能執行完指令。新增資料耗時約 0.01 秒。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-Y65AVHDDB7r-xB_cAcxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e758AS4IkF8Qb-YmwZ99Og.png" /></figure><ul><li>有索引</li></ul><p>在 title 欄位新增索引，搜尋時間會降低到低於 0.01 秒。同樣觀察一下怎麼執行的，這次 key 顯示 title_index， rows 是 1，表示成功地用索引加速了搜尋。但新增資料耗時提高到 0.03 秒。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*189b_yqz-X_Hzd30n_P2qg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBiIlJZCWFdoRTzBFGzodA.png" /></figure><p><strong>正向及反向索引？</strong></p><p>改一下情境，現在想用書籍簡介來找書。例如，想找簡介有提到「狗狗」的書。這裡要搜的東西從一個完整的欄位，變成可能為欄位的一部分，而關鍵字也可能出現在欄位裡的任何位置，這稱為全文檢索（Full-Text Search）。</p><p>用上述索引方式依簡介的字首排序來新增索引的話，會發現搜尋時還是得檢視每筆資料，比對其中字元，才能確定中綴、後綴是否包含了「狗狗」。顯然全文檢索的情境下，我們需要改變索引的設計。</p><p>想法是這樣，既然想要看到「狗狗」就知道對應資料的位置，就把「狗狗」這個字設成索引。那「貓貓」跟其他人類好夥伴呢？沒問題，都設索引。如果有很多筆資料都出現「狗狗」，就把所有的資料都記下來。</p><p>相比上述書名用的索引叫正向索引（forward index），這種按指定規則擷取原始資料一部分字詞（token），紀錄字詞出現過的資料的索引，就叫反向索引（inverted index）。一些簡介會這麼說：</p><ul><li>正向索引：文件對應字詞（documents — terms），像章節目錄</li><li>反向索引：字詞對應文件（terms — documents），像關鍵字索引</li></ul><p>不過兩者本質都是「內容 — 位置」的對應，所以正、反向就先理解成約定俗成。討論上，一般講索引指的多是正向索引，反向索引會指明是反向索引。</p><blockquote>There’s no mystery to uncover here. Otherwise the two types are identical, it’s just a question of what information you <strong>have</strong>, and as a result what information you’re trying to <strong>find.</strong></blockquote><p>實際例子，MySQL 的 fulltext index 就是反向索引。用 books 感受一下：清空表格，新增 5 筆假資料，summary 欄位加上 fulltext index。</p><pre>CREATE FULLTEXT INDEX summary_index ON books (summary);</pre><p>輸入下列指令，可以看到簡介內的字詞確實被擷取出來當成索引了。</p><pre>SET GLOBAL innodb_ft_aux_table = &#39;test/books&#39;;<br><br>SELECT WORD, DOC_ID, POSITION FROM INFORMATION_SCHEMA.INNODB_FT_INDEX_TABLE;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*Lnv7kNPhvg_4VCsBciz51A.png" /></figure><p>不過也會發現 ”and” 這種不具辨識意義的字，竟然也被紀錄了 3 次。這裡就涉及了要怎麼設定停用詞的問題，先不討論，只記錄一下，可以用下列指令查看 InnoDB 的預設停用詞，如不敷使用，可另外設定用自訂的停用詞表。</p><pre>SELECT * FROM INFORMATION_SCHEMA.INNODB_FT_DEFAULT_STOPWORD;</pre><p>除了停用詞，視個案需求，使用反向索引可能也會設定分詞規則。例如上圖，可以猜想到 MySQL 預設是用「空格」來區分字詞，這在英文資料固然沒問題，但中文資料的話，就無法用空格區分，得設定成其他的分詞規則。</p><blockquote>The built-in MySQL full-text parser uses the white space between words as a delimiter to determine where words begin and end, which is a limitation when working with ideographic languages that do not use word delimiters.</blockquote><p><strong>整理</strong></p><ol><li>索引是「內容 — 位置」的對應關係，用來加速資料查找</li><li>索引「使用得當」可加速資料查找，但會消耗磁碟空間，讓資料更新變慢</li><li>已經有太多索引了、欄位太常更新或內容差異太小，較不適合設定索引</li><li>MySQL 可透過 explain 檢視特定指令有沒有用到、用了什麼索引</li><li>反向索引用來加速全文檢索，其內容是從原始資料抓出來的字詞</li><li>視個案需求而定，使用反向索引可能會自訂停用詞、分詞規則</li></ol><p><strong>參考資料</strong></p><ol><li><a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-fulltext-index.html#innodb-fulltext-index-design">InnoDB Full-Text Index Design</a></li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/explain-output.html#explain_filtered">EXPLAIN Output Format</a></li><li><a href="https://dev.mysql.com/doc/refman/8.0/en/fulltext-search-ngram.html">ngram Full-Text Parser</a></li><li><a href="https://stackoverflow.com/questions/7727686/whats-the-difference-between-an-inverted-index-and-a-plain-old-index">What’s the difference between an inverted index and a plain old index?</a></li><li><a href="https://dev.to/im_bhatman/series/7439">Understanding Inverted Indexes (3 Part Series)</a></li><li><a href="https://www.elastic.co/blog/found-indexing-for-beginners-part3">Indexing for Beginners, Part 3</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1824d7c79782" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elasticsearch 怎麼用？]]></title>
            <link>https://medium.com/@mortonkuo/%E4%BB%80%E9%BA%BC%E6%98%AF-elasticsearch-2af2304aed0b?source=rss-7fb06f307fdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2af2304aed0b</guid>
            <category><![CDATA[kibana]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Morton Kuo]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 13:12:47 GMT</pubDate>
            <atom:updated>2022-11-12T15:12:11.843Z</atom:updated>
            <content:encoded><![CDATA[<h3>Elasticsearch 怎麼用 ?</h3><h4>在 AWS EC2 上用 Docker 快速啟動 ES 單一節點</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4HRk1wUu5-9jv-xH" /></figure><p>Elasticsearch 是美籍荷蘭公司 Elastic 推出的搜尋引擎、NoSQL Database，是該公司整體產品 Elastic Stack（也叫 ELK Stack）的核心。根據官方介紹，它的特點包括能快速回應搜尋結果、可彈性微調搜尋的關聯性、能讓分析大量資料變得輕鬆。如果你的搜尋功能是要對大量資料進行全文檢索，而且你覺得快還要更快，那就可以考慮使用 Elasticsearch。</p><p><strong>怎麼用？例示幾個方式</strong></p><ol><li>在 AWS EC2 上，啟動 Docker 的 ES container</li><li><a href="https://www.elastic.co/downloads/elasticsearch">下載執行 elasticsearch.bat</a> （或本機啟動 Docker 的 ES container）</li><li>透過 <a href="https://www.elastic.co/cloud/">Elastic Cloud</a>，在指定 Cloud Service 上運行</li></ol><p><strong>啟動 ES container</strong></p><p>啟動 EC2 instance，OS 映像檔選 Amazon Linux 2，Memory 選 4 GB 以上。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*0T8WFFmMKVz2TXutV5J8Eg.png" /></figure><p>安裝並啟動 Docker，把 EC2 使用者加入有權使用 Docker 的群組，避免之後要一直 sudo。加入群組後，要重新連線到 EC2，才適用得到新的權限設定。</p><pre>sudo amazon-linux-extras install docker<br><br>sudo systemctl start docker<br><br>sudo usermod -aG docker ec2-user</pre><p>由於下面會用 ELK 的 Kibana 來修改 ES 密碼，ES 要跟 Kibana 建立連線，所以先建立連線用的 network。如果容器關閉，ES 裡的資料會跟著消失，因此也一併建立 volume。</p><pre>docker pull docker.elastic.co/elasticsearch/elasticsearch:8.5.0<br><br>docker network create elastic<br><br>docker volume create elastic</pre><p>這裡如果直接啟動 ES 容器，會發生錯誤，顯示 virtual memory 不夠。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTGrO_vc79KzFquTZ61dag.png" /></figure><p>所以我們先設定一下，編輯 sysctl.conf，寫下 vm.max_map_count=262144。輸入下方 sysctl 指令，適用新的設定。</p><pre>sudo vim /etc/sysctl.conf<br><br>sudo sysctl --system</pre><p>可以啟動 ES 容器了，把 network、volume 掛進去。</p><pre>docker run --name es01 --net elastic -p 9200:9200 -p 9300:9300 -v elastic:/usr/share/elasticsearch/data -it docker.elastic.co/elasticsearch/elasticsearch:8.5.0</pre><p>啟動後，終端機先別關，畫面上有後續設定及登入需要的密碼、Tokens，只會出現一次，記錄下來。把自動生成的憑證複製到 EC2 ，透過 curl 確認一下 ES 是否正常運作，密碼就輸入上方記錄的預設密碼。</p><pre>docker cp es01:/usr/share/elasticsearch/config/certs/http_ca.crt .<br><br>curl --cacert http_ca.crt -u elastic:password https://localhost:9200</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vfV_G_eeDjgDJuWf5LNIw.png" /></figure><p><em>You Know, for Search</em>，正常運作。</p><p>這裡就成功的在 EC2 上用 Docker 啟動一個 ES 節點了！</p><p><strong>透過 Kibana 修改密碼</strong></p><p>但我們想用 Kibana 自訂 ES 密碼，所以繼續啟動 Kibana 的容器。一樣 Pull 映像檔下來，把 network 掛進去。</p><pre>docker pull docker.elastic.co/kibana/kibana:8.5.0<br><br>docker run --name kib-01 --net elastic -p 5601:5601 docker.elastic.co/kibana/kibana:8.5.0</pre><p>畫面停止滾動後，一樣先別關終端機，瀏覽器輸入 http://0.0.0.0:5601（ domain 要換成 EC2 的 Public IP，EC2 的 Security Group 的 Inbound Rule 要允許訪問 port 5601）可以看到漂亮的 Kibana 設定頁面。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bqmk1Ei0GjIL1nuJUB1_8A.png" /></figure><p>表示 Kibana 正常運行中。貼上 ES 容器啟動時顯示的 Kibana Enrollment Token，點選 Configure Elastic，並輸入終端機顯示的驗證碼進行驗證，就可以看到登入頁面了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*AMFBzm0HeIFK8i6C9EtxRg.png" /></figure><p>但目前瀏覽器跟 Kibana 是用 HTTP 在溝通，送出敏感資料的話，會讓網路上的人看光光，所以這裡先不登入，來設定 HTTPS。</p><p>流程上，可以進入 ES 容器使用內建工具 elasticsearch-certutil，製作憑證跟私鑰，把兩者直接放到 Kibana 容器裡，設定用 HTTPS 溝通。但這作法，瀏覽器會不認得憑證的簽署者，存取頁面會顯示不安全連線警告。</p><p>為了讓瀏覽器直接判斷憑證由受信任的簽署者核發，這裡作法是：用上述內建工具製作憑證簽署請求（CSR）及私鑰，提供 CSR 給 CA 簽署，把 CA 核發的憑證連同私鑰放到 Kibana 容器裡。</p><p>另外，因為製作 CSR 輸入憑證基本資訊時要輸入 Kibana 所在 domain，且 CA 也會要求證明對 domain 有擁有權，所以事先用 Route 53 新增了一個 domain 並把它指向 Kibana 容器所在的 EC2。</p><p>正式進入 ES 容器，輸入下指令選擇製作 CSR 、輸入事先準備的自訂網域，會拿到一個包含了 CSR、私鑰的壓縮檔。</p><pre>./bin/elasticsearch-certutil http</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*_ZctBjXTSR6cPWFCFck2pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*MWILw4fvK6iZizjWNKI88w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIwezgwpg83AuBiwx9VLpg.png" /></figure><p>解壓縮後，把 CSR 交給所選的 CA 申請憑證。</p><pre>unzip elasticsearch-ssl-http.zip</pre><p>這裡向 <a href="https://app.zerossl.com/">ZeroSSL</a> 申請簽署憑證，把 CSR 貼進它對應的申請欄位。</p><pre>cat elasticsearch/the-csr.csr</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bszNJEsLSnXkCqSCSwDbXg.png" /></figure><p>下載 CA 核發的憑證，上傳到 EC2後，把憑證跟私鑰一起放進 Kibana 容器。</p><pre>docker cp es01:/usr/share/elasticsearch/elasticsearch/your-private-key.key .<br><br>docker cp your-private-key.key kib-01:/usr/share/kibana<br><br>docker cp certificate.crt kib-01:/usr/share/kibana</pre><p>可以開始編輯 Kibana 的設定檔了。為了編輯設定檔，直接用 root 身份進入 Kibana 容器，安裝 vim。</p><pre>docker exec -u 0 -it es01 /bin/bash<br><br>apt-get update<br><br>apt-get -y install vim</pre><p>編輯 config 資料夾裡的 kibana.yml，寫入下列設定。</p><pre>server.ssl.enabled: true<br>server.ssl.key: /usr/share/kibana/your-private-key.key<br>server.ssl.certificate: /usr/share/kibana/certificate.crt</pre><p>重啟 Kibana 容器，瀏覽器輸入自訂網址，可以用 HTTPS 跟 Kibana 了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYXB6zTlTojGo__04fYTLg.png" /></figure><p>登入之後，左方選單依序點選 Stack Management、Users，選擇預設使用者 elastic ，修改密碼！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2af2304aed0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>