在elasticsearch中查询最大日期

我需要从弹性搜索索引文档的日期时间字段中获取最新日期。基本上,我有这个查询,我直接在 elasticsearch 中返回我需要的内容:


GET localhost:9200/index-name/_search


    {

        "aggs" : {

           "max_date": {"max": {"field": "dateTime"}}

        }

    }

我需要在 Go 中执行相同的查询。我看到 Olivere 库中有一个 MaxAgregation,但我不确定如何使用它。有人知道该怎么做吗?


紫衣仙女
浏览 2418回答 3
3回答

慕森王

以下是如何开始使用 go 库。实例化 a 后client,您可以执行以下操作:maxDateAgg := NewMaxAggregation().Field("dateTime")builder := client.Search().Index("index-name").Pretty(true)builder = builder.Aggregation("max_date", maxDateAgg)之后,调用.Do(ctx).builder

ABOUTYOU

我设法使它与答案之一和我已经拥有的一些东西一起工作:maxDateAgg := elastic.NewMaxAggregation().Field("dateTime") builder := esClient.Search().Index("index-name").Pretty(true) builder = builder.Aggregation("max_datetime", maxDateAgg) builder = builder.Size(1).Sort("dateTime",false) searchResult, err := builder.Do(ctx) 这将返回具有最大日期时间的文档中的所有字段,因此我创建了一个结构,并将 search.hit.hit 源 json.unmarshall 放入结构中,因此我只能从结构中获取日期时间字段。

小唯快跑啊

对于那些想知道如何获取日期的人ctx := context.Background()termQuery := elastic.NewMatchAllQuery()agg := elastic.NewMaxAggregation().Field("le_nested.last_updated")sr, err := elastic.Client.Search("your_index").Query(termQuery).Aggregation("max_date", agg).Do(ctx)if err != nil {    m := fmt.Sprint("Error getting getting last updated data", err)    fmt.Println(m)}max, found := sr.Aggregations.MaxBucket("max_date")if !found {    m := fmt.Sprint("max_date aggregation not found", err)    fmt.Println(m)}fmt.Println("MAX DATE", max.ValueAsString)tm := int64(*max.Value) / 1000mu := time.Unix(tm, 0)fmt.Println("DATE", mu)ES 以毫秒为单位返回日期,无需解组任何内容
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go