说明
我下述示例代码基于GoFrame框架。
用Go一分钟对接ElasticSearch,前提是你已经搭建好了Es服务。
创建链接
- 我使用的es版本是v7
- 引入的logs是托管到gitlab的日志库,读者对接的时候不用管这里,用go或者goframe原生的日志库就可以
- 该方法返回es的客户端对象以供实例方法调用
package elastic import ( "github.com/gogf/gf/frame/g" "github.com/olivere/elastic/v7" "gitlab.xxx.com/xxxx/library.git/logs" "log" "os" ) func connection() (search *elastic.Client, err error) { opts := []elastic.ClientOptionFunc{ elastic.SetURL("http://" + g.Cfg().Get("Es.Url").(string)), elastic.SetSniff(false), elastic.SetBasicAuth(g.Cfg().Get("Es.UserName").(string), g.Cfg().Get("Es.Password").(string)), elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags)), elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC ", log.LstdFlags)), } client, err := elastic.NewClient(opts...) if err != nil { logs.Error("Es 链接失败 error:【%v】", err) } return client, err }
其中g.Cfg().Get
是从配置文件中读取ES配置参数
配置文件示例:
/config/config.toml
[Es] Url = "192.168.26.xxx:9200" UserName = "xxx" Password = "xxx" IndexGoods = "xxxx_index"
封装方法
封装请求文档的方法:
- 创建和es的链接
- 设置链接超时的时间
- 设置请求参数:索引、id
func GetDoc(req GetDocReq) (docContent *elastic.GetResult, err error) { client, err := connection() if err != nil || client == nil { err = errors.New("elastic连接失败:" + err.Error()) return } defer client.Stop() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() docContent, err = client.Get().Index(req.IndexName).Id(req.DocId).Do(ctx) if err != nil { err = errors.New("获取文档失败,错误原因:" + err.Error()) logs.Error("获取文档失败 错误原因:【%s】", err.Error()) return } return }
调用示例
非常简单:
- 定义好请求结构体
- 调用我们上面封装好的方法就可以了
type GetDocReq struct { DocId string `json:"doc_id"` IndexName string `json:"index_name"` } func TestDocId() { res, err := GetDoc(GetDocReq{ DocId: "goods_35138650", //文档Id IndexName: "goods_app_index", //索引名称 }) if err != nil { g.Dump("err:", err) } g.Dump(res) } 复制代码
打印结果
铛铛铛~
是不是非常简单,我说的一分钟搞定对接ES没有骗人吧~
{ "_index": "goods_app_index", "_type": "_doc", "_id": "goods_35138650", "_uid": "", "_routing": "", "_parent": "", "_version": 1, "_seq_no": 674993, "_primary_term": 5, "_source": { "gross_profit_rate": 173, "drop_reason": null, "shop_id": 40054, "real_sale": 0, "groups_ids": "", "max_profits": 228, "activity_ids": "", "total_stock": 999, "default_goods_id": 0, "discount": 8.300000190734863, "channel_id": 0, "third_category_name": "母婴用品,喂养用品,儿童餐具", "promotion_rate": 209, "stock": 999, "id": 35138650, "agreement_price": 1090, "is_free_shipping": true, "updated_time": 1649407211, "my_join_field": { "name": "goods" }, "choose_count": 2, "unit": "", "title": "超市-儿童餐具盛广达米妮宽柄汤匙", "old_goods_title": "超市-儿童餐具盛广达米妮宽柄汤匙", "sale": 1231, "market_price": 5100, "brand_id": 258407, "guide_price": 1318, "activity_price": 0, "recommend": 1, "real_source": 0, "cover": "http://gfs17.gomein.net.cn/T1FLbzBvDv1RCvBVdK", "goods_tag_ids": "6", "min_profits": 228, "real_month_return_sale": 0, "type": "goods", "created_time": 1649234396, "goods_type": true, "real_return_sale": 0, "dis_category_id": "683983-683984-683985", "source": 10, "push_status": 0, "third_brand_name": "盛广达", "activity_rate": 0, "third_id": 43557, "origin": "", "status": 1, "category_id": "1-1007-1007015", "real_month_sale": 0, "psoriasis": false }, "found": true }