如何在复合聚合中对存储桶进行排序?
我需要使用Bucket排序进行复合聚合。
我试过排序聚合。
我尝试了复合聚合。

最佳答案

我认为这个问题是您先前的question的延续,因此被认为是相同的用例

添加带有索引数据,映射,搜索查询和搜索结果的工作示例
索引映射:

{
  "mappings":{
    "properties":{
      "user":{
        "type":"keyword"
      },
      "date":{
        "type":"date"
      }
    }
  }
}
索引数据:
{
  "date": "2015-01-01",
  "user": "user1"
}
{
  "date": "2014-01-01",
  "user": "user2"
}
{
  "date": "2015-01-11",
  "user": "user3"
}
搜索查询:
{
  "size": 0,
  "aggs": {
    "my_buckets": {
      "composite": {
       "size": 3,               <-- note this
        "sources": [
          {
            "product": {
              "terms": {
                "field": "user"
              }
            }
          }
        ]
      },
      "aggs": {
        "mySort": {
          "bucket_sort": {
            "sort": [
              {
                "sort_user": {
                  "order": "desc"
                }
              }
            ]
          }
        },
        "sort_user": {
          "min": {
            "field": "date"
          }
        }
      }
    }
  }
}
搜索结果:
"aggregations": {
    "my_buckets": {
      "after_key": {
        "product": "user3"
      },
      "buckets": [
        {
          "key": {
            "product": "user3"
          },
          "doc_count": 1,
          "sort_user": {
            "value": 1.4209344E12,
            "value_as_string": "2015-01-11T00:00:00.000Z"
          }
        },
        {
          "key": {
            "product": "user1"
          },
          "doc_count": 1,
          "sort_user": {
            "value": 1.4200704E12,
            "value_as_string": "2015-01-01T00:00:00.000Z"
          }
        },
        {
          "key": {
            "product": "user2"
          },
          "doc_count": 1,
          "sort_user": {
            "value": 1.3885344E12,
            "value_as_string": "2014-01-01T00:00:00.000Z"
          }
        }
      ]
    }

10-02 03:06
查看更多