【问题标题】:Query max date in elasticsearch在elasticsearch中查询最大日期
【发布时间】:2020-11-18 15:09:57
【问题描述】:

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

GET localhost:9200/index-name/_search

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

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

【问题讨论】:

标签: go elasticsearch aggregate


【解决方案1】:

下面是 to get started 使用 go 库的方法。

实例化client 后,您可以执行以下操作:

maxDateAgg := NewMaxAggregation().Field("dateTime")

builder := client.Search().Index("index-name").Pretty(true)
builder = builder.Aggregation("max_date", maxDateAgg)

之后,在builder 上拨打.Do(ctx)。

【讨论】:

  • 谢谢!我设法使它与您的答案和我已经拥有的一些东西一起使用: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 放入结构中,所以我只能使用日期时间。再次感谢!
  • 听起来不错。如果对您有帮助,请随时投票和接受:-)
【解决方案2】:

我设法使它与一个答案和我已经拥有的一些东西一起工作:

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 放入结构中,因此我只能从结构中获取日期时间字段。

【讨论】:

    【解决方案3】:

    对于那些想知道如何获取日期的人

    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) / 1000
    mu := time.Unix(tm, 0)
    fmt.Println("DATE", mu)
    

    ES 以毫秒为单位返回日期,无需解组任何内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-04
      • 2018-03-20
      • 2022-01-03
      • 2012-01-09
      • 1970-01-01
      • 2015-09-19
      • 2015-02-22
      • 2018-02-26
      相关资源
      最近更新 更多