環境
- Elasticsearch 2.3.5
- Elasticsearch-ik-plugin
實現
- 搜索建議的對象
假設有以下兩個json對象,需要對其中tags字段進行搜索建議:
//對象Product1
{
"title": "Product1",
"description": "Product1 Description",
"tags": [
"山東",
"山東高新開發區",
"山東大學",
"two columns",
"wordpress"
]
}
//對象Product2
{
"title": "Product2",
"description": "Product2 Description",
"tags": [
"山東省",
"山東公安局",
"山東檢察院",
"skrill",
"wordland"
]
}
- 設置索引mapping
建立索引suggester_ik_test和mapping,如下:
注意使用的suggester類型為completion
curl -XPUT "http://10.110.13.57:9200/suggester_ik_test?pretty" -d'
{
"mappings": {
"product": {
"properties": {
"description": {
"type": "string"
},
"tags": {
"type": "string"
},
"title": {
"type": "string"
},
"tag_suggest": {
"type": "completion",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word",
"payloads": false
}
}
}
}
}'
- 索引數據
根據上述索引和mapping對json數據建立索引:
//Product1
curl -XPUT "http://10.110.13.57:9200/suggester_ik_test/product/1?pretty" -d'
{
"title": "Product1",
"description": "Product1 Description",
"tags": [
"山東",
"山東高新開發區",
"山東大學",
"two columns",
"wordpress"
],
"tag_suggest": {
"input": [
"山東",
"山東高新開發區",
"山東大學",
"two columns",
"wordpress"
]
}
}'
//Product2
curl -XPUT "http://10.110.13.57:9200/suggester_ik_test/product/2?pretty" -d'
{
"title": "Product2",
"description": "Product2 Description",
"tags": [
"山東省",
"山東公安局",
"山東檢察院",
"skrill",
"wordland"
],
"tag_suggest": {
"input": [
"山東省",
"山東公安局",
"山東檢察院",
"skrill",
"wordland"
]
}
}'
- 測試
搜索“山東”,查看是否有搜索建議提示生效:
curl -XPOST "http://10.110.13.57:9200/suggester_ik_test/_suggest?pretty" -d'
{
"product_suggest":{
"text":"山東",
"completion": {
"field" : "tag_suggest"
}
}
}'
//應該得到以下數據
{
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"product_suggest" : [ {
"text" : "山東",
"offset" : 0,
"length" : 2,
"options" : [ {
"text" : "山東",
"score" : 1.0
}, {
"text" : "山東公安局",
"score" : 1.0
}, {
"text" : "山東大學",
"score" : 1.0
}, {
"text" : "山東檢察院",
"score" : 1.0
}, {
"text" : "山東省",
"score" : 1.0
} ]
} ]
}
參考資料
Quick and Dirty Autocomplete with Elasticsearch Completion Suggest