英文:
How to filter Elasticsearch results in Go by time ranges?
问题
我正在使用olivere的v.5 elasticsearch库(https://godoc.org/github.com/olivere/elastic)。
我正在尝试做类似于这篇帖子的事情,该帖子使用v.2库(https://stackoverflow.com/questions/32674666/how-to-search-in-elasticsearch-with-go-filtering-results-by-time-frames)。
但是,在v.5中没有'NewRangeFilter'和'NewFilteredQuery'。在v.5中有一个'DateRange' API(https://godoc.org/github.com/olivere/elastic#Aggregations.DateRange),我可以从聚合中调用它,但它接受一个字符串作为参数,所以我不知道应该传入什么。
这是我到目前为止尝试构建聚合的代码。之后,我不确定应该传入DateRange函数的参数是什么。我有一个名为'tmpindex'的索引和一个名为'user'的类型,每个文档都有一个'时间戳'属性,它是一个整数。
timeline := elasticClient.NewTermsAggregation().Field("timestamp").Size(10).OrderByCountDesc()
searchResult, err := elasticClient.Search().
Index("tmpindex"). // 在索引“tmpindex”中搜索
Aggregation("timeline", timeline).
From(0).Size(10). // 获取文档0-9
Pretty(true). // 格式化打印请求和响应的JSON
Do(context.Background()) // 执行
if err != nil {
return err
}
英文:
I'm using olivere's v.5 elasticsearch library - https://godoc.org/github.com/olivere/elastic
Trying to do something similar to this post which uses the v.2 library - https://stackoverflow.com/questions/32674666/how-to-search-in-elasticsearch-with-go-filtering-results-by-time-frames
But 'NewRangeFilter' and 'NewFilteredQuery' are not available in v.5.
There is a 'DateRange' API in v.5 (https://godoc.org/github.com/olivere/elastic#Aggregations.DateRange) that I can call from an Aggregation, but it takes in a string, so I don't know what I'm supposed to pass in.
This is what I've tried so far to build an aggregation. After that, I'm not sure what to pass into the DateRange function. I have an index called 'tmpindex' and type called 'user' and each document has a 'timestamp' property which is an integer.
timeline := elasticClient.NewTermsAggregation().Field("timestamp").Size(10).OrderByCountDesc()
searchResult, err := elasticClient.Search().
Index("tmpindex"). // search in index "tmpindex"
Aggregation("timeline", timeline).
From(0).Size(10). // take documents 0-9
Pretty(true). // pretty print request and response JSON
Do(context.Background()) // execute
if err != nil {
return err
}
答案1
得分: 9
我认为你正在寻找范围查询。
你可以像这样使用它...
query := elastic.NewBoolQuery().
Filter(elastic.NewRangeQuery("timestamp").
From(start).
To(end))
其中 start
和 end
是 time.Time 类型的值,"timestamp"
是你的时间字段的名称。
需要注意的是,将其包装在 Bool Query 的过滤器中只是其中一种使用方式。它可以在任何可以传递查询的地方使用。
英文:
I think you're looking for Range Query.
You'd use it something like this...
query := elastic.NewBoolQuery().
Filter(elastic.NewRangeQuery("timestamp").
From(start).
To(end))
Where start
and end
are time.Time values and "timestamp"
is the name of your time field.
I should note that wrapping it in a filter of a Bool Query is just one way to use it. It can be used anywhere you can pass a Query.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论