1. 程式人生 > >elasticSearch 分詞器踩的坑

elasticSearch 分詞器踩的坑

elasticSearch 作為搜尋引擎,效率是非常高的。在搜尋引擎的選擇上,一般是solr和es。兩者都是基於lucene的。經簡單調研,目前美團酒旅與外賣使用的都是以elasticSearch為主。

es的預設分詞器對中文的支援非常不好,所以要使用es,分詞器是必須要配置的。以下記錄es分詞器配置過程中踩的坑。

 

首先ik 分詞器與es版本是有嚴格依賴的,參考git文件 https://github.com/medcl/elasticsearch-analysis-ik

 

安裝過程參考官網文件。

安裝好了以後在設定ik為預設分詞器

配置elasticsearch.yml

增加

index:    analysis:                        analyzer:            
ik:            alias: [ik_analyzer]            type: org.elasticsearch.index.analysis.IkAnalyzerProvider        ik_max_word:           
type: ik            use_smart:  false        ik_smart:            type: ik            use_smart:  true index.analysis.analyzer. default .type: ik 或者簡寫為 index.analysis.analyzer.ik.type: "ik" 6:重啟elasticsearch kill -9 currentThread  ./elasticsearch -d

這是網上比較普遍的版本,但是設定好了以後測試發現並不生效,還是使用的預設的standard analyzer ,這是怎麼回事... 

後來反覆嘗試多次無果最後參考ik 分詞器作者issue。發現問題。https://github.com/medcl/elasticsearch-analysis-ik/issues/269

es 節點層面的預設分詞設定已經廢棄,不支援了。

解決方法:法一:在索引層面動態設定。

例:

 

PUT http://localhost:9200/index1
{
"settings": {
"refresh_interval": "5s",
"number_of_shards" : 1, // 一個主節點
"number_of_replicas" : 0 // 0個副本,後面可以加
},
"mappings": {
"_default_":{
"_all": { "enabled": false } // 關閉_all欄位,因為我們只搜尋title欄位
},
"resource": {
"dynamic": false, // 關閉“動態修改索引”
"properties": {
"title": {
"type": "string",
"index": "analyzed",
"fields": {
"cn": {
"type": "string",
"analyzer": "ik"
},
"en": {
"type": "string",
"analyzer": "english"
}
}
}
}
}
}
}

如上常見索引後,使用java api 用法如下

boolQueryBuilder.must(QueryBuilders.termQuery("title.cn","迎"));(使用title.cn 不能只用title)

親測可用。

法二(ik 作者推薦):使用索引模版,關於模版的用法參考官方文件,這裡給出自測demo

curl -XPUT 'http://localhost:9200/_template/moban' -d '
{
"template": "te*",
"settings": {
"number_of_shards": 1
},
"mappings": {
"type1": {
"_source": {
"enabled": false
},
"properties": {
title: {
"type": "string",
"analyzer": "ik"
}
}
}
}
}'

建立模版後 title 欄位有效,java api 同上。