集成ElasticSearch客户端

1991/6/26 Gin框架

# 1.介绍

Elasticsearch(ES)是一个基于Lucene构建的开源、分布式、RESTful接口的全文搜索引擎。Elasticsearch还是一个分布式文档数据库,其中每个字段均可被索引,而且每个字段的数据均可被搜索,ES能够横向扩展至数以百计的服务器存储以及处理PB级的数据。可以在极短的时间内存储、搜索和分析大量的数据。通常作为具有复杂搜索场景情况下的核心发动机。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎。

# 1.1 集成流程

# 2.安装

这里使用olivere/elastic@注意: 下载包的版本需要和ES版本相同,如我们这里使用的ES是7.13.3的版本,那么我们就需要下载olivere/elastic/v7

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

# 3. 配置

# 3.1 编辑主配置文件

文件位置:./config.yaml

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

# 3.2 新增配置结构体

文件位置: ./config/elastic.go

type elasticConfig struct {
 Url                 string        `yaml:"url"`
 Sniff               bool          `yaml:"sniff"`
 HealthCheckInterval time.Duration `yaml:"healthCheckInterval"`
 LogPre              string        `yaml:"logPre"`
 commonConfig
}
1
2
3
4
5
6
7

# 3.3 嵌入主配置

编辑文件:./config/app.go

// ServerConfig 配置信息
type ServerConfig struct {
 ...
 Elastic elastic `yaml:"elastic"`
}
1
2
3
4
5

# 3.4 定义全局变量

编辑文件:./global/global.go

// 变量
var (
  ...
 GvaElastic *elastic.Client// ES客户端
)
1
2
3
4
5

# 4. 集成代码

# 4.1 集成入口

编辑文件:./main.go

func init() {
 ...
 // 初始化elasticSearch
 initialize.InitES()
}
func main() {
 // 启动服务
 ...
}
1
2
3
4
5
6
7
8
9

# 4.2 创建客户端

新建文件:./initialize/elastic.go

// 创建es客户端
func InitES() {
 // 配置
 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(global.GvaLogger),
   elastic.SetInfoLog(global.GvaLogger),
  )
  if err != nil {
   panic("创建ES客户端错误:" + err.Error())
  }
  global.GvaElastic = client
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 5. 测试使用

# 5.1 创建控制器

新建文件:./api/v1/es_api.go

// 索引库
const indexName = "go-test"

// 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)
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 5.2 注册路由

新建文件:./api/v1/es_router.go

// 注册es相关路由
func InitESRouter(engine *gin.Engine) {
 esGroup := engine.Group("es")
 {
  esGroup.GET("searchById", v1.SearchById)
 }
}
1
2
3
4
5
6
7

# 5.3 请求返回

# 请求
curl -XGET http://127.0.0.1:8080/es/searchById?id=5
# 返回
{"code":0,"msg":"请求成功","data":{"name":"李四","age":22,"birth":"1992-04-25"}}
1
2
3
4