elasticsearch 使用同義詞
使用環境
-
elasticsearch5.1.1
-
kibana5.1.1
-
同義詞插件5.1.1
安裝插件
下載對應的elasticsearch-analysis-dynamic-synonym-5.1.1.zip, 解壓到本地的elasticsearch/plugins目錄下, 重新啟動es
第一種方式本地文件
說明:
-
對於本地文件:主要通過文件的修改時間戳(Modify time)來判斷是否要重新加載
-
在elasticsearch/config目錄下,建立analysis目錄, 並在analysis目錄下放入synonym.txt, 在文件首行加入下面一行同義詞,來進行測試
西紅柿, 番茄, 聖女
es設置索引和自定義解析器
PUT /megacorp
{
"mappings": {
"employee": {
"properties": {
"name":{
"type": "text",
"analyzer": "ik-index", //指定索引時候用的解析器
"search_analyzer": "ik-smart" //指定搜索時候用的解析器
}
}
}
}
,
"settings": {
"analysis": {
"filter": {
"local_synonym" : {
"type" : "dynamic_synonym",
"synonyms_path" : "analysis/synonym.txt"
}
},
"analyzer": {
"ik-index": {
"type": "custom",
"tokenizer": "ik_max_word",
"filter": [
"local_synonym" //對同義詞進行了過濾
]
},
"ik-smart": {
"type": "custom",
"tokenizer": "ik_smart",
"filter": [
"local_synonym"
]
}
}
}
}
}
設置好后,可以用以下命令查看,同義詞是否配置成功
GET /megacorp/_analyze
{
"analyzer": "ik-index",
"text": "西紅柿"
}
正確分詞結果如下:
{
"tokens": [
{
"token": "西紅柿",
"start_offset": 0,
"end_offset": 3,
"type": "CN_WORD",
"position": 0
},
{
"token": "番茄",
"start_offset": 0,
"end_offset": 3,
"type": "SYNONYM",
"position": 0
},
{
"token": "聖女",
"start_offset": 0,
"end_offset": 3,
"type": "SYNONYM",
"position": 0
}
]
}
插入2條數據:
PUT /megacorp/employee/1
{
"name" : "聖女果"
}
PUT /megacorp/employee/2
{
"name" : "番茄"
}
搜索西紅柿, 會搜索出番茄和聖女果的記錄:
GET /megacorp/employee/_search
{
"query":{
"match": {
"name": "西紅柿"
}
}
}
第二種方式遠程接口
說明:
-
這個http請求需要返回兩個頭部,一個是 Last-Modified,一個是 ETag,只要有一個發生變化,該插件就會去獲取新的同義詞來更新相應的同義詞。
本地寫個接口
http://localhost/synonym/list
該接口返回的需要設置以下三個屬性
$response->setLastModified($lastModified);
$response->setEtag($etag, true);
$response->headers->set('Content-Type', 'text/plain');
注:
nginx 在開啟了 gzip 之后,如果有 ETAG 則會調用 ngx_http_clear_etag 將其清除,
解決的辦法很簡單:
只要 PHP 返回的 ETAG 是 weak ETAG,那么就一切都會正常起來了。而所謂的 weak ETAG,也就是弱 ETAG,它是相對於正常 ETAG 而言的,表現形式就是 ETAG 前面加上 W/
W/"db8b38e8a3257a2f195b727eceb2c5d3"
下面是設置遠程, 本地同義詞的配置
PUT /megacorp
{
"mappings": {
"employee": {
"properties": {
"name":{
"type": "text",
"analyzer": "ik-index", //指定索引時候用的解析器
"search_analyzer": "ik-smart" //指定搜索時候用的解析器
}
}
}
}
,
"settings": {
"analysis": {
"filter": {
"remote_synonym": {
"type" : "dynamic_synonym",
"synonyms_path" : "http://localhost/synonym/list",
"interval": 60 // 沒60s調取一次接口
},
"local_synonym" : {
"type" : "dynamic_synonym",
"synonyms_path" : "analysis/synonym.txt"
}
},
"analyzer": {
"ik-index": {
"type": "custom",
"tokenizer": "ik_max_word",
"filter": [
"remote_synonym", //對遠程同義詞進行了過濾
"local_synonym" //對本地同義詞進行了過濾
]
},
"ik-smart": {
"type": "custom",
"tokenizer": "ik_smart",
"filter": [
"local_synonym"
]
}
}
}
}
}