我对 Go 编程还很陌生。
我正在尝试创建一个简单的程序,它只做一件事,通过 elasticsearch API 搜索字符串。 我的问题特定于我正在使用的“gopkg.in/olivere/elastic.v2”包。
这是一个代码示例:
package main
import (
"fmt"
"gopkg.in/olivere/elastic.v2"
"log"
"reflect"
)
type Syslog struct {
Program string
Message string
Timestamp string
}
func main() {
client, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"))
if err != nil {
log.Fatal(err)
}
info, code, err := client.Ping().Do()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Elasticsearch returned with code %d and version %s", code, info.Version.Number)
termQuery := elastic.NewTermQuery("message", "configuration")
searchResult, err := client.Search().
//PostFilter(postFilter).
Index("logstash-*"). // search in index "logstash-*"
Query(&termQuery). // specify the query
Sort("timestamp", true). // sort by "message" field, ascending
From(0).Size(10). // take documents 0-9
Pretty(true). // pretty print request and response JSON
Do() // execute
if err != nil {
log.Fatal(err)
}
fmt.Printf(" Query took %d milliseconds\n", searchResult.TookInMillis)
var ttyp Syslog
for _, item := range searchResult.Each(reflect.TypeOf(ttyp)) {
t := item.(Syslog)
fmt.Printf("Found %s %s %s\n", t.Timestamp, t.Program, t.Message)
}
}
这可行,但我真正想要的是按时间范围限制搜索。
据我所知,我需要使用 FilteredQuery 函数。但我迷失了如何创建过滤查询的尝试。
有创建它的函数“FilteredQuery”,它需要查询类型作为输入参数,但没有创建查询本身的函数。我可以只创建一个所需类型的变量,它仍然需要有字段,例如在 elasticsearch 中查找的字段和要查找的字符串。
在调用 func (FilteredQuery) Filter
时,Filter 变量也是如此。
可能有人已经有了示例,或者可以为我指明正确的方向。
我有一个 JSON 示例,如果传递给 elastcisearch,它会得到我想要的:
"query": {
"filtered": {
"query": {
"query_string": {
"query": "message:\"configuration\"",
"analyze_wildcard": true
}
},
"filter": {
"bool": {
"must": [
{
"range": {
"@timestamp": {
"gte": 1442100154219,
"lte": 1442704954219
}
}
}
],
"must_not": []
}
}
}
},
但我不知道如何在 Go 中实现相同的功能。谢谢。
最佳答案
这是一个产生你想要的结果的例子:
package main
import (
"encoding/json"
"fmt"
elastic "gopkg.in/olivere/elastic.v2"
)
func main() {
termQuery := elastic.NewTermQuery("message", "configuration")
timeRangeFilter := elastic.NewRangeFilter("@timestamp").Gte(1442100154219).Lte(1442704954219)
// Not sure this one is really useful, I just put it here to mimic what you said is the expected result
boolFilter := elastic.NewBoolFilter().Must(timeRangeFilter)
query := elastic.NewFilteredQuery(termQuery).Filter(boolFilter)
queryBytes, err := json.MarshalIndent(query.Source(), "", "\t")
if err != nil {
panic(err)
}
fmt.Println(string(queryBytes))
}
它产生的输出是:
{
"filtered": {
"filter": {
"bool": {
"must": {
"range": {
"@timestamp": {
"from": 1442100154219,
"include_lower": true,
"include_upper": true,
"to": 1442704954219
}
}
}
}
},
"query": {
"term": {
"message": "configuration"
}
}
}
}
关于elasticsearch - 如何使用 Go 按时间范围过滤结果在 elasticsearch 中进行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32674666/