如何在“存储桶”内相对于“按字母顺序”对聚合函数进行排序

时间:2020-11-06 16:20:27

标签: elasticsearch dsl

我在DSL查询中具有汇总功能,

聚合功能是根据“存储桶”中的doc_count排序的。

如何在“存储桶”中相对于“按字母顺序”对聚合函数进行排序

下面是DSL查询

{
  'from': 0,
  'size': 20,
  'aggs': {
    'Employee': {
      'terms': {
        'field': 'employee.name.keyword'
      }
    },
    'Role': {
      'terms': {
        'field': 'role.name.keyword'
      }
    },
    'Designation': {
      'terms': {
        'field': 'designation.name.keyword'
      }
    }
  },
  'query': {
    'bool': {
      'must': [
        {
          'terms': {
            'role.name.keyword': [
              'Developer'
            ]
          }
        }
      ],
      'filter': [
        {
          'term': {
            'parent.keyword': 'Server'
          }
        }
      ]
    }
  }
}

我的汇总函数内部

'aggregations': {'employee': {'doc_count_error_upper_bound': 0,
   'sum_other_doc_count': 0,
   'buckets': [{'key': 'Gold', 'doc_count': 3},
    {'key': 'A', 'doc_count': 1},
    {'key': 'B', 'doc_count': 1}]},
  'designation': {'doc_count_error_upper_bound': 0,
   'sum_other_doc_count': 0,
   'buckets': [{'key': 'Commercial', 'doc_count': 4},
    {'key': 'Enterprise', 'doc_count': 2},
    {'key': 'TEST_BUSINESS_AREA_1', 'doc_count': 1}]},
  'role': {'doc_count_error_upper_bound': 0,
   'sum_other_doc_count': 0,
   'buckets': [{'key': 'role1', 'doc_count': 3},
    {'key': 'role2', 'doc_count': 1}]}}

1 个答案:

答案 0 :(得分:1)

如果您想按字母顺序(以升序)对字段进行排序, 试试下面的查询:

{
  "from": 0,
  "size": 20,
  "aggs": {
    "Employee": {
      "terms": {
        "field": "employee.name.keyword",
        "order": { "_key" : "asc" }           <-- note this
      }
    },
    "Role": {
      "terms": {
        "field": "role.name.keyword",
        "order": { "_key" : "asc" }        <-- note this
      }
    },
    "Designation": {
      "terms": {
        "field": "designation.name.keyword",
        "order": { "_key" : "asc" }             <-- note this
      }
    }
  },
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "role.name.keyword": [
              "Developer"
            ]
          }
        }
      ],
      "filter": [
        {
          "term": {
            "parent.keyword": "Server"
          }
        }
      ]
    }
  }
}