【问题标题】:Elasticsearch - Get aggregation key sort as numberElasticsearch - 将聚合键排序为数字
【发布时间】:2017-02-03 13:15:22
【问题描述】:

我做了聚合一些数据的查询结果,它的聚合键是数字。我试图按键对聚合结果进行排序。 elasticsearch 将键视为字符串。

由于当前结果桶的数量很大,无法在客户端进行修改。有这个想法吗?

这是我的查询。

"aggregations" : {
                "startcount" : {
                    "terms" : {
                        "script" : "round(doc['startat'].value/1000)",
                        "size" : 1000,
                        "order" : { "_term" : "asc" }
                    }
                }
             }

和当前结果桶。

    "buckets": [
       {
          "key": "0",
          "doc_count": 68
       },
       {
          "key": "1",
          "doc_count": 21
       },
       {
          "key": "10",
          "doc_count": 6
       },
       {
          "key": "11",
          "doc_count": 16
       },

这是我的预期结果。

"buckets": [
   {
      "key": "0",
      "doc_count": 68
   },
   {
      "key": "1",
      "doc_count": 21
   },
   {
      "key": "2", // not '10'
      "doc_count": 6
   },
   {
      "key": "3", // not '11'
      "doc_count": 16
   },

【问题讨论】:

  • 在你的映射中,startat字段有什么类型?
  • 类型是'date',格式是'strict_date_optional_time||epoch_millis'。
  • 我最好使用 date_histogram。谢谢你给我另一个观点。
  • 也许你应该更详细地解释你的用例,并可能添加一个示例文档来说明它。
  • 我需要按时间段计算。 date_histogram 非常适合我的情况。我需要知道的最后一件事是它的 date_histogram 键应该是数字,而不是像“yyyy-MM-dd HH”。

标签: elasticsearch aggregation


【解决方案1】:

使用value_script 方法应该可以解决字母排序问题:

例子:

 {
   "size": 0,
   "aggregations": {
      "startcount": {
         "terms": {
            "field": "startat",
            "script": "round(_value/1000)",
            "size": 1000,
            "order": {
               "_term": "asc"
            }
         }
      }
   }
}

【讨论】:

  • @keety 有没有办法在脚本中接收doc_count 值?
  • 类似这样的东西:"script": "round(_value/1000) * doc_count",
  • #!弃用:已弃用的聚合顺序键 [_term] 已使用,由 [_key] 替换。
猜你喜欢
  • 2018-11-15
  • 2015-01-23
  • 2021-01-30
  • 2016-04-12
  • 2022-01-26
  • 2021-11-06
  • 2021-02-11
  • 2016-04-13
  • 2015-11-06
相关资源
最近更新 更多