【问题标题】:How to sort buckets by doc_count?如何按 doc_count 对存储桶进行排序?
【发布时间】:2023-01-10 17:01:17
【问题描述】:
GET /civile/_search
{
  "size": 0,
  "query": {
    "match": {
      "distretto": "MI"
    }
  },
  "aggs": {
    "our_buckets": {
      "composite": {
        "size": 1000,
        "sources": [
          { "codiceoggetto": { "terms": { "field": "codiceoggetto.keyword", "order": "desc" } } }
        ]
      }
    }
  }
}

我的 Elasticsearch 查询通过 distretto =“MI”匹配文档。 使用 size = 0 我隐藏结果。

但最重要的是我定义了 our_buckets 聚合。 它返回 1000 个键并在 codiceoggetto.keyword 字段上执行“分组依据”。

现在我想按 doc_count 排序我的存储桶结果!我能怎么做?

这里的回应

{
  "took" : 20,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 10000,
      "relation" : "gte"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "our_buckets" : {
      "after_key" : {
        "codiceoggetto" : "010001"
      },
      "buckets" : [
        {
          "key" : {
            "codiceoggetto" : "490999"
          },
          "doc_count" : 3
        },
        {
          "key" : {
            "codiceoggetto" : "481312"
          },
          "doc_count" : 1
        },

【问题讨论】:

    标签: sorting elasticsearch


    【解决方案1】:

    你可以使用bucket_sort来完成

    {
      "size": 0,
      "query": {
        "match": {
          "distretto": "MI"
        }
      },
      "aggs": {
        "our_buckets": {
          "composite": {
            "size": 1000,
            "sources": [
              {
                "codiceoggetto": {
                  "terms": {
                    "field": "codiceoggetto.keyword",
                    "order": "desc"
                  }
                }
              }
            ]
          },
          "aggs": {
            "sort_by_count": {
              "bucket_sort": {
                "sort": [
                  {
                    "_count": {
                      "order": "desc"
                    }
                  }
                ]
              }
            }
          }
        }
      }
    }
    

    【讨论】:

    • 您好,今天我测试了您的查询,但它不起作用。我得到"type" : "parsing_exception", "reason" : "Unknown aggregation type [sort_by_count]"。我该如何解决?
    • 我使用 doc_count 作为排序字段,但错误更改为 named_object_not_found_exception
    猜你喜欢
    • 2019-01-27
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 2016-09-08
    • 2018-07-26
    • 2015-12-30
    • 2019-09-15
    • 2021-05-06
    相关资源
    最近更新 更多