【问题标题】:Sorting after aggregation in Elasticsearch在 Elasticsearch 中聚合后排序
【发布时间】:2015-08-25 21:51:25
【问题描述】:

我有这种结构的文档:

{
    FIELD1:string,
    FIELD2:
        [ {SUBFIELD:number}, {SUBFIELD:number}...]
}

我想对 FIELD2.SUBFIELDs 中数字总和的结果进行排序:

GET myindex/_search
{
  "size":0,
  "aggs": {
    "a1": {
      "terms": { 
        "field": "FIELD1",
        "size":0
      },
      "aggs":{
        "a2":{
          "sum":{
            "field":"FIELD2.SUBFIELD"
          }
        }
      }
    }
  }
}

如果我这样做,我会获得未排序的存储桶,但我想要按“a2”值排序的存储桶。 我怎么能做到这一点? 谢谢!

【问题讨论】:

    标签: sorting elasticsearch aggregation


    【解决方案1】:

    你几乎拥有它。您只需将order property 添加到您的a1 术语聚合中,如下所示:

    GET myindex/_search
    {
      "size":0,
      "aggs": {
        "a1": {
          "terms": { 
            "field": "FIELD1",
            "size":0,
            "order": {"a2": "desc"}      <--- add this
          },
          "aggs":{
            "a2":{
              "sum":{
                "field":"FIELD2.SUBFIELD"
              }
            }
          }
        }
      }
    }
    

    【讨论】:

    • 谢谢...我不知道“订单”在哪里
    • 谢谢!拯救了我的一天!在文档上找不到这个,这很明显:)
    • @ErdalG。文档或订购条款聚合为here
    • @Val 当a2 是scripted_metric 聚合时,这不起作用。我将它用于我必须使用 scripted_metric 聚合的情况。我收到了这个错误"reason": { "type": "aggregation_execution_exception", "reason": "Invalid terms aggregation order path [totalViews]. Terms buckets can only be sorted on a sub-aggregator path that is built out of zero or more single-bucket aggregations within the path and a final single-bucket or a metrics aggregation at the path end." }
    • @saeedzhiany 正确,有一个 open PR 和一个 open issue 关于这个。
    【解决方案2】:

    来自 Val https://stackoverflow.com/users/4604579/val 的辉煌

    基本上是一样的,但是这对我来说是为每个“名称”找到最大的“大小”,并显示前 25 个最大的:

    {
      "size": 0,
      "aggs": {
        "agg1": {
          "terms": {
            "field": "name.keyword",
            "order": {
              "agg2": "desc"
            },
            "size": 25
          },
          "aggs": {
            "agg2": {
              "max": {
                "field": "size"
              }
            }
          }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 1970-01-01
      • 2015-01-23
      • 2021-02-11
      • 2016-04-12
      • 2016-04-13
      • 2015-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多