1.介绍

ElasticSearch是一个分布式、可扩展、近实时的高性能搜索与数据分析引擎。在Go中经常使用的包有以下两个:

文档 Star 数量
olivere/elastic https://olivere.github.io/elastic/ 5.7k
elastic/go-elasticsearch https://github.com/elastic/go-elasticsearch 3.2k

2.安装

使用olivere/elastic

1
2
# 安装v7的版本
go get github.com/olivere/elastic/v7

3.配置

3.1 编写配置文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
elastic:
  # 是否开启
  enable: true
  # 服务地址,多个地址用逗号隔开
  url: http://127.0.0.1:9200
  # 是否转换请求地址,默认为true,当等于true时 请求http://ip:port/_nodes/http,将其返回的url作为请求路径
  sniff: false
  # 心跳检测间隔
  healthCheckInterval: 5s
  # 日志前缀
  logPre: ES-

3.2 编写配置结构体

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
/**
 * elastic
 * @Description: ES配置
 **/
type elastic struct {
    Enable              bool          `yaml:"enable"`              // 是否开启
    Url                 string        `yaml:"url"`                 // 服务地址,多个地址用逗号隔开
    Sniff               bool          `yaml:"sniff"`               // 是否转换请求地址,默认为true,当等于true时 请求http://ip:port/_nodes/http,将其返回的url作为请求路径
    HealthCheckInterval time.Duration `yaml:"healthCheckInterval"` // 心跳检测间隔
    LogPre              string        `yaml:"logPre"`              // 日志前缀
}

3.3 加载配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// 启动加载
func SetLoadInit() {
    // 初始化全局配置文件
    initConfig()
    // 初始化zap日志
    initLogger()
    // 初始化gorm
    initGorm()
    // 初始化redis
    initRedis()
    // 初始化es
    initElastic()
    // 定时任务
    initCron()
}

4.初始化ES客户端

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// 创建es客户端
func initElastic() {
    // 配置
    elasticConfig := global.GvaConfig.Elastic
    if elasticConfig.Enable {
        fmt.Printf("elasticConfig: %v\n", elasticConfig)
        // 创建客户端
        client, err := elastic.NewClient(
            elastic.SetURL(elasticConfig.Url),
            elastic.SetSniff(elasticConfig.Sniff),
            elastic.SetHealthcheckInterval(elasticConfig.HealthCheckInterval),
            elastic.SetErrorLog(log.New(os.Stderr, elasticConfig.LogPre+"ERROR ", log.LstdFlags)),
            elastic.SetInfoLog(log.New(os.Stderr, elasticConfig.LogPre+"INFO ", log.LstdFlags)),
        )
        if err != nil {
            panic("创建ES客户端错误:" + err.Error())
        }
        global.GvaElastic = client
    }
}

5.使用

5.1 创建索引

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// CreateIndex 创建索引
func CreateIndex(ctx *gin.Context) {
    userMapping := `{
        "mappings":{
            "properties":{
                "name":{
                    "type":"keyword"
                },
                "age":{
                    "type":"byte"
                },
                "birth":{
                    "type":"date"
                }
            }
        }
    }`
    // 判断索引是否存在
    exist, _ := global.GvaElastic.IndexExists(indexName).Do(ctx)
    if exist {
        response.Error(ctx, "索引已经存在,无需重复创建!")
        return
    }
    res, err := global.GvaElastic.CreateIndex(indexName).BodyString(userMapping).Do(ctx)
    if err != nil {
        response.Error(ctx, "创建索引失败,无需重复创建!")
        return
    }
    response.OkWithData(ctx, res)
}

5.2 查询

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// SearchById 查询
func SearchById(ctx *gin.Context) {
    id, _ := ctx.GetQuery("id")
    res, err := global.GvaElastic.Get().Index(indexName).Id(id).Do(ctx)
    if err != nil {
        response.Error(ctx, fmt.Sprintf("查询失败:%s", err))
        return
    }
    response.OkWithData(ctx, res.Source)
}