连接es代码
$ cat loges.go
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/elastic/go-elasticsearch/v7"
)
func Loges(msg string, dateIndex string) {
addresses := []string{"http://10.20.9.105:9200"}
config := elasticsearch.Config{
Addresses: addresses,
Username: "elastic",
Password: "rxyn38#*",
CloudID: "",
APIKey: "",
}
// new client
es, err := elasticsearch.NewClient(config)
fmt.Println(err, "Error creating the client")
res, err := es.Info()
fmt.Println(err, "Error getting response")
// fmt.Println(res.String())
var buf bytes.Buffer
query := map[string]interface{}{
"query": map[string]interface{}{
"match": map[string]interface{}{
"msg": msg,
},
},
"highlight": map[string]interface{}{
"pre_tags": []string{"<font color='red'>"},
"post_tags": []string{"</font>"},
"fields": map[string]interface{}{
"title": map[string]interface{}{},
},
},
}
if err := json.NewEncoder(&buf).Encode(query); err != nil {
fmt.Println(err, "Error encoding query")
}
// Perform the search request.
res, err = es.Search(
es.Search.WithContext(context.Background()),
es.Search.WithIndex(dateIndex),
es.Search.WithBody(&buf),
es.Search.WithTrackTotalHits(true),
es.Search.WithPretty(),
)
if err != nil {
fmt.Println(err, "Error getting response")
}
defer res.Body.Close()
// return res.String()
fmt.Println(res.String())
}
main代码
$ cat main.go
package main
import (
"flag"
)
var (
msg string
dateIndex string
)
func init() {
flag.StringVar(&msg, "msg", "检验是否满足xx条件", "输入要匹配的内容")
flag.StringVar(&dateIndex, "dateIndex", "log_prod-2021-03-11", "输入要搜索的索引")
}
func main() {
flag.Parse()
Loges(msg, dateIndex)
}
编译构建
go build -o loges.exe .\main.go .\loges.go
执行
./loges.exe -msg "校验是否满足xx条件" -dateIndex "log_prod-2021-03-17"
有疑问加站长微信联系(非本文作者)