搜索突然挂了。一脸懵逼。因为这个搜索服务是我1年前搭建的。啥都忘记了。现在整理下,将来可以参考。说明下,我的服务器一台,用docker-swarm 跑的服务。
搭服务
es 服务
search:
image: elasticsearch:7.6.2
ports:
- xxx:9200
- xxx:9300
volumes:
- /path/prd/es/data:/usr/share/elasticsearch/data
- /path/prd/es/plugins:/usr/share/elasticsearch/plugins
- /path/prd/es/config/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml
environment:
path.data: '/usr/share/elasticsearch/data'
discovery.type: 'single-node'
ES_JAVA_OPTS: '-Xms2048m -Xmx4096m'
ps: 敏感信息用 path和xxx 替换了。
elastichd 在线query
为了方便查询和查看服务。
安装了eshd
eshd:
image: containerize/elastichd
ports:
- xxxx:9800
这样服务就正常了。
ps: 注意我链接的是search, 因为容器的名字 我取得是search( 不要照搬)
数据同步-monstache
我这里用的是mongodb数据库。
mongo-es:
image: registry.cn-beijing.aliyuncs.com/aixunpan/mongo-es
volumes:
- /path/prd/mongo-es/config.toml:/config/config.toml
command: -f /config/config.toml
自动增量同步。也就是会监听mongo的
服务数据异常了:
sudo docker exec -ti 2a56dba70f78 /bin/monstache -f /config/config.toml
重新同步下。2a56dba70f78是容器id.
镜像搭建
git clone git@github.com:rwynn/monstache.git
docker pull rwynn/monstache-builder-cache-rel6:1.0.7
cd monstache
docker build -t mongo-es .
可以参考: https://blog.youkuaiyun.com/weixin_45753881/article/details/126019511
代码接入
我用的go-zero框架,但是mongo没用他的,当时我用的时候不好使。
import "gopkg.in/mgo.v2/bson"
...
func (l *SearchCompaniesLogic) SearchLikeNameOrEqID(req types.SearchReq) (*types.PageResult, error) {
//query := elastic.NewTermQuery("name", req.Keyword) // =
req.Keyword = strings.TrimSpace(req.Keyword)
var query elastic.Query
if len(req.Keyword) > 0 {
if bson.IsObjectIdHex(req.Keyword) {
query = elastic.NewMatchQuery("_id", strings.ToLower(req.Keyword)) // like
} else {
query = elastic.NewFuzzyQuery("name", strings.ToLower(req.Keyword)) // like
}
} else {
query = elastic.NewMatchQuery("flag", 1)
}
result, err := l.svcCtx.Client.Search().Index("overseas.companies").Query(query).From(req.Offset).Size(req.Limit).Pretty(true).Do(l.ctx)
if err != nil {
return &types.PageResult{}, err
}
resp := types.PageResult{}
resp.Total = int(result.Hits.TotalHits.Value)
items := []models.Company{}
if resp.Total > 0 {
for _, hit := range result.Hits.Hits {
var com models.Company
err := json.Unmarshal(hit.Source, &com)
if err == nil {
com.ID = bson.ObjectIdHex(hit.Id)
com.Fill(l.svcCtx.Config.UploadConfig)
items = append(items, com)
}
}
}
resp.Size = req.Limit
resp.Page = req.Offset/req.Limit + 1
for _, item := range items {
resp.Items = append(resp.Items, item)
}
return &resp, nil
}
总结
框架用的go-zero
搜索服务用的elasticsearch
mongo 链接库用的gopkg.in/mgo.v2/bson
数据同步用的monstache
es面板用的elastichd