代码如下:
package main
import (
"context"
"fmt"
"github.com/olivere/elastic/v7"
)
var client *elastic.Client
var host = "http://192.168.204.111:9200"
//初始化
func init() {
//errorlog := log.New(os.Stdout, "APP", log.LstdFlags)
var err error
//这个地方有个小坑 不加上elastic.SetSniff(false) 会连接不上
client, err = elastic.NewClient(elastic.SetSniff(false), elastic.SetURL(host))
if err != nil {
panic(err)
}
_,_,err = client.Ping(host).Do(context.Background())
if err != nil {
panic(err)
}
//fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)
esversion,err := client.ElasticsearchVersion(host)
if err != nil {
panic(err)
}
fmt.Printf("Elasticsearch version %s\n", esversion)
}
func main() {
//CreateIndex()
//ExistsIndex()
//CloseIndex()
//DelIndex()
OpenIndex()
fmt.Println("处理完成。")
}
/*
创建索引
*/
func CreateIndex() {
mapping := `{
"settings": {
"index":{
"max_result_window": "1000000000"
}
},
"mappings": {
"properties": {
"TAC": {
"type": "keyword"
},
"cardId": {
"type": "keyword"
},
"electricalPercentage": {
"type": "integer"
},
"enAxleCount": {
"type": "integer"
},
"enTime": {
"type": "date",
"null_value": "null",
"format": "[yyyy-MM-dd HH:mm:ss]"
}
}
}
}`
createIndex,err := client.CreateIndex("enIndex_20211129").BodyString(mapping).Do(context.Background())
if err != nil{
fmt.Println(err)
}else{
if !createIndex.Acknowledged{
fmt.Println("创建失败")
}else {
fmt.Println("创建成功")
}
}
AddAliasses()
}
/*
删除索引
*/
func DelIndex() {
client.DeleteIndex("enIndex_20211128").Do(context.Background())
}
/*
判断索引是否存在
*/
func ExistsIndex() {
exist,err:=client.IndexExists("enIndex_20211128").Do(context.Background())
if err!= nil{
}
if !exist{
fmt.Println("不存在")
}else {
fmt.Println("存在")
}
}
/*
索引添加别名
*/
func AddAliasses() {
client.Alias().Add("enIndex_20211129","enIndex").Do(context.Background())
}
/*
关闭索引
*/
func CloseIndex() {
client.CloseIndex("enIndex_20211129").Do(context.Background())
}
/*
打开索引
*/
func OpenIndex() {
client.OpenIndex("enIndex_20211129").Do(context.Background())
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)