本次主要采用单例模式生成elasticsearch 服务,然后服务自带put和delete方法。调用的时候需要先调用 NewElasticServer 方法生成该服务。后续再根据需要调用服务的方法。。
package elastic
import (
"context"
"ginweb/config"
"ginweb/runtime"
"github.com/olivere/elastic"
"log"
"os"
"strconv"
"sync"
)
var host = config.ElasticHost
type Elastic struct {
Client *elastic.Client
}
var server *Elastic
var mu sync.Mutex
// @title NewElasticServer
// @description 返回一个Elastic 对象
// @return *Elastic Elastic 对象
func NewElasticServer() *Elastic {
mu.Lock()
defer mu.Unlock()
if server == nil {
server = &Elastic{}
log := log.New(os.Stdout, "APP", log.LstdFlags)
var err error
server.Client, err = elastic.NewClient(elastic.SetErrorLog(log), elastic.SetURL(host))
if err != nil {
panic(err)
}
info, code, err := server.Client.Ping(host).Do(context.Background())
if err != nil {
panic(err)
}
runtime.Info.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)
_, err = server.Client.ElasticsearchVersion(host)
if err != nil {
panic(err)
}
}
return server
}
// @title PUT
// @description ES添加数据指定id
// @auth 曹修康 时间(2020/9/8 10:57 )
// @param index string 索引名字
// @param types string 文档类型
// @param id uint32 文档id
// @param body interface 数据(可以json化)
// @return put2 *elastic.IndexResponse 插入结果
// @return err error 错误信息
func (e *Elastic) Put(index string, types string, id uint32, body interface{}) (put2 *elastic.IndexResponse, err error) {
put2, err = e.Client.Index().
Index(index).
Type(types).
Id(strconv.Itoa(int(id))).
BodyJson(body).
Do(context.Background())
return
}
// @title Delete
// @description ES删除指定id数据
// @auth 曹修康 时间(2020/9/8 10:57 )
// @param index string 索引名字
// @param types string 文档类型
// @param id uint32 文档id
// @return res string 删除结果
// @return err error 错误信息
func (e *Elastic) Delete(index string, types string, id uint32) (res string, err error) {
_, err = e.Client.Delete().Index(index).
Type(types).
Id(strconv.Itoa(int(id))).
Do(context.Background())
if err != nil {
res = err.Error()
return
}
res = "ok"
return
}