1.介绍
ElasticSearch
是一个分布式、可扩展、近实时的高性能搜索与数据分析引擎。在Go中经常使用的包有以下两个:
2.安装
使用olivere/elastic
1 2
| 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 sniff: false healthCheckInterval: 5s logPre: ES-
|
3.2 编写配置结构体
1 2 3 4 5 6 7 8 9 10 11
|
type elastic struct { Enable bool `yaml:"enable"` Url string `yaml:"url"` Sniff bool `yaml:"sniff"` 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() initLogger() initGorm() initRedis() initElastic() initCron() }
|
4.初始化ES客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 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
| 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
| 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) }
|