golang使用elasticsearch

本次主要采用单例模式生成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
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值