2019独角兽企业重金招聘Python工程师标准>>>
目的:实现淘宝、京东搜索建议功能
准备环境:安装elasticsearch, 并安装拼音插件(https://github.com/medcl/elasticsearch-analysis-pinyin)。我安装的环境为当前最新版6.2.4。
参考官网教程:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters-completion.html
docker中安装:docker exec -it elastic-search /bin/bash
elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-pinyin/releases/download/v6.4.1/elasticsearch-analysis-pinyin-6.4.1.zip
不同的地方是要整合拼音进去。
1、创建Index
PUT suggester
{
"index" : {
"analysis" : {
"analyzer" : {
"pinyin_analyzer" : {
"tokenizer" : "my_pinyin"
}
},
"tokenizer" : {
"my_pinyin" : {
"type" : "pinyin",
"keep_separate_first_letter" : true,
"keep_original" : true
}
}
}
}
}
2、创建Mapping(type要相同)
POST /suggester/User/_mapping
{
"User" : {
"properties" : {
"suggest" : {
"type" : "completion",
"analyzer":"pinyin_analyzer"
},
"title" : {
"type": "completion",
"analyzer":"pinyin_analyzer"
}
}
}
}
3、添加测试数据
PUT /suggester/User/1
{
"title":"我是帅哥",
"suggest":"今天我要出去耍"
}
PUT /suggester/User/2
{
"title":"我是美女",
"suggest":"今天我不出去耍"
}
4、搜索
POST /suggester/_search
{
"suggest": {
"song-suggest" : {
"prefix" : "wos",
"completion" : {
"field" : "title"
}
}
}
}
结果