本文主要介绍如何使用ElasticSearch搭建网址链接的sug服务。
在mysql中存储网址数据,使用task任务定时同步数据到es集群,用户请求服务端接口,服务端请求es获取suggestion数据返回给用户。
本项目主要使用了ElasticSearch的Completion Suggester:
Completion Suggester
es索引定义
curl -X PUT 10.16.59.xx:9200/hao_mysite/mysite/_mapping -d '
{
"mysite": {
"properties": {
"name-sug": {
"type": "completion",
"analyzer": "standard",
"search_analyzer": "standard"
},
"url-sug": {
"type": "completion",
"analyzer": "standard",
"search_analyzer": "standard"
},
"name": {
"type": "string"
},
"url": {
"type": "string"
}
}
}
}
'
由于本项目有两个接口,一个是网站名字的suggestion,一个是网站url的suggestion,所以定义了两个type为completion的字段分别来进行suggest。
定时更新es数据
本项目使用es的bulk接口来进行数据的批量更新:
BULK接口文档
在mysql数据库表结构中有edit_time字段,每次更新或者新添加数据的时候都会将edit_time更新到当前时间,我们记录一个上次更新到的时间点,然后每次增量的选择edit_time在上次更新时间点到当前时间之间的数据,进行数据的更新,这样实现了数据的更新机制。
添加单条数据的接口如下:
curl -X PUT '10.16.59.xx:9200/hao_mysite/mysite/1?refresh=true' -d '
{
"name-sug": {
"input": [
"12306"
],
"weight": 34
},
"url-sug": {
"input": [
"12306.cn"
],
"weight": 34
},
"name": "12306",
"url": "www.12306.cn"
}
'
suggest搜索
curl -X POST '10.16.59.xx:9200/hao_mysite/mysite/_search?pretty' -d '
{
"suggest": {
"mysite-suggest": {
"prefix": "www",
"completion": {
"field": "url-sug"
}
}
}
}
'