在弹性搜索中如何使用复合聚合对字段进行排序

问题描述

如何在弹性搜索中对具有复合聚合的字段进行排序。

我们正在使用弹性搜索版本6.8.6,并尝试使用复合聚合对字段进行排序。 但是我们无法通过汇总获得预期的结果。

这是我们的映射

{
  "properties": {
    "department": {
      "type": "text","fields": {
        "keyword": {
          "ignore_above": 256.0,"type": "keyword"
        }
      }
    },"project": {
      "type": "text","billingUnit": {
      "type": "text","billingType": {
      "type": "text","application": {
      "type": "text","environmet": {
      "type": "text","cost": {
      "type": "float"
    }
  }
}

通过使用以下查询,我们无法进行排序,结果不按字母顺序排列:

{
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
            "department": {
              "query": "HR","slop": 0,"zero_terms_query": "NONE","boost": 1.0
            }
          }
        }
      ],"adjust_pure_negative": true,"boost": 1.0
    }
  },"sort": [
    {
      "project.keyword": {
        "order": "desc"
      }
    }
  ],"aggs": {
    "TERM_RANGE": {
      "composite": {
        "size": 10000,"sources": [
          {
            "billingUnitKey": {
              "terms": {
                "field": "billingUnit.keyword","missing_bucket": false
              }
            }
          },{
            "billingTypeKey": {
              "terms": {
                "field": "billingType.keyword","missing_bucket": false
              }
            }
          }
        ]
      },"aggregations": {
        "TOTAL": {
          "sum": {
            "field": "cost"
          }
        },"dataHits": {
          "top_hits": {
            "from": 0,"size": 1,"version": false,"seq_no_primary_term": false,"explain": false,"_source": {
              "includes": [
                "application.keyword","environmet.keyword",],"excludes": []
            },"docvalue_fields": [
              {
                "field": "application.keyword"
              },{
                "field": "environmet.keyword"
              }
            ]
          }
        },"paginate_bucket": {
          "bucket_sort": {
            "sort": [],"from": 0,"size": 100,"gap_policy": "SKIP"
          }
        }
      }
    }
  }
}

在以下查询中进行排序(没有聚合)可以很好地工作

{
  "query": {
    "match": {
      "department": "HR"
    }
  },"sort": [
    {
      "project.keyword": {
        "order": "desc"
      }
    }
  ]
}

解决方法

您应该使用复合聚合的orderhttps://www.elastic.co/guide/en/elasticsearch/reference/7.8/search-aggregations-bucket-composite-aggregation.html#_order

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...