可以通过关键字和时间间隔进行查询,关键字可以像kibana上的查询语句填写,代码搞起
//搜索返回的内容
type Result struct {
Message string `json:"message"`
Source string `json:"source"`
//Host string `json:"host"`
}
type SearchEs struct {
}
func NewSearchEs() *SearchEs {
return &SearchEs{}
}
func (s *SearchEs) GetMessage(alerts model.Alerts) ([]Result,error) {
fmt.Println("开始通过es查找关键字。。。",alerts.KeyWorld)
boolQuery := elastic.NewBoolQuery()
stringQuery := elastic.NewQueryStringQuery(alerts.KeyWorld)
//查询时间时间
startTime := "now-" + alerts.IntervalTime + "m"
rangeQuery := elastic.NewRangeQuery("@timestamp").Gte(startTime).Lte("now")
boolQuery.Filter(stringQuery,rangeQuery)
//index前缀+index时间
indexTime := time.Now().Format("2006.01.02")
fmt.Println(indexTime)
index := alerts.IndexName + "-" + indexTime
fmt.Println(index)
//查询
res,err := es.EsClient.Search(index).Query(boolQuery).Sort("@timestamp",false).Do(es.Ctx)
if err !=nil{
log.Println("查询失败,",err)
return nil, err
}
fmt.Println("查询命中次数,",res.TotalHits())
if res.TotalHits() > 0 {
fmt.Println("开始转换值")
data := NewSearchEs().SearchValue(res)
return data,nil
}
return nil, err
}
//转换需要返回的数据
func (s *SearchEs) SearchValue(res *elastic.SearchResult) []Result {
var result Result
data := make([]Result,0)
fmt.Println(res.TotalHits())
for _,item := range res.Each(reflect.TypeOf(result)){
t := item.(Result)
fmt.Println("查询结果为,",t)
data = append(data, t)
}
return data
}
标签:res,fmt,查询,神器,Println,Result,go,data,es
From: https://www.cnblogs.com/aiverhua/p/16615674.html