使用 Elasticsearch ik分詞實現同義詞搜索(轉)


1、首先需要安裝好Elasticsearch 和elasticsearch-analysis-ik分詞器

2、配置ik同義詞

 

Elasticsearch 自帶一個名為 synonym 的同義詞 filter。為了能讓 IK 和 synonym 同時工作,我們需要定義新的 analyzer,用 IK 做 tokenizer,synonym 做 filter。聽上去很復雜,實際上要做的只是加一段配置。

打開 /config/elasticsearch.yml 文件,加入以下配置:

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. index:  
  2.   analysis:  
  3.     analyzer:  
  4.       ik_syno:  
  5.           type: custom  
  6.           tokenizer: ik_max_word  
  7.           filter: [my_synonym_filter]  
  8.       ik_syno_smart:  
  9.           type: custom  
  10.           tokenizer: ik_smart  
  11.           filter: [my_synonym_filter]  
  12.     filter:  
  13.       my_synonym_filter:  
  14.           type: synonym  
  15.           synonyms_path: analysis/synonym.txt  

以上配置定義了 ik_syno 和 ik_syno_smart 這兩個新的 analyzer,分別對應 IK 的 ik_max_word 和 ik_smart 兩種分詞策略。根據 IK 的文檔,二者區別如下:

  • ik_max_word:會將文本做最細粒度的拆分,例如「中華人民共和國國歌」會被拆分為「中華人民共和國、中華人民、中華、華人、人民共和國、人民、人、民、共和國、共和、和、國國、國歌」,會窮盡各種可能的組合;
  • ik_smart:會將文本做最粗粒度的拆分,例如「中華人民共和國國歌」會被拆分為「中華人民共和國、國歌」;

ik_syno 和 ik_syno_smart 都會使用 synonym filter 實現同義詞轉換。

3、創建/config/analysis/synonym.txt 文件,輸入一些同義詞並存為 utf-8 格式。例如

到此同義詞配置已經完成,重啟ES即可,搜索時指定分詞為ik_syno或ik_syno_smart。

創建Mapping映射。執行curl命令如下

 

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. curl -XPOST  http://192.168.1.99:9200/goodsindex/goods/_mapping -d'{  
  2.   "goods": {  
  3.     "_all": {  
  4.       "enabled": true,  
  5.       "analyzer": "ik_max_word",  
  6.       "search_analyzer": "ik_max_word",  
  7.       "term_vector": "no",  
  8.       "store": "false"  
  9.     },  
  10.     "properties": {  
  11.       "title": {  
  12.         "type": "string",  
  13.         "term_vector": "with_positions_offsets",  
  14.         "analyzer": "ik_syno",  
  15.         "search_analyzer": "ik_syno"  
  16.       },  
  17.       "content": {  
  18.         "type": "string",  
  19.         "term_vector": "with_positions_offsets",  
  20.         "analyzer": "ik_syno",  
  21.         "search_analyzer": "ik_syno"  
  22.       },  
  23.       "tags": {  
  24.         "type": "string",  
  25.         "term_vector": "no",  
  26.         "analyzer": "ik_syno",  
  27.         "search_analyzer": "ik_syno"  
  28.       },  
  29.       "slug": {  
  30.         "type": "string",  
  31.         "term_vector": "no"  
  32.       },  
  33.       "update_date": {  
  34.         "type": "date",  
  35.         "term_vector": "no",  
  36.         "index": "no"  
  37.       }  
  38.     }  
  39.   }  
  40. }'  

以上代碼為 test 索引下的 article 類型指定了字段特征: title 、 content 和 tags 字段使用 ik_syno 做為 analyzer,說明它使用 ik_max_word 做為分詞,並且應用 synonym 同義詞策略; slug 字段沒有指定 analyzer,說明它使用默認分詞;而 update_date 字段則不會被索引。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM