Elasticsearch Ordering terms aggregation buckets after field in top hits sub aggregation

夙愿已清 提交于 2019-12-11 09:55:11

问题


I would like to order the buckets from a terms aggregation based on a property possessed by the first element in a top hits aggregation.

My best effort query looks like this (with syntax errors):

{
    "aggregations": {
        "toBeOrdered": {
            "terms": {
                "field": "parent_uuid",
                "size": 1000000,
                "order": {
                    "topAnswer._source.id": "asc"
                }
            },
            "aggregations": {
                "topAnswer": {
                    "top_hits": {
                        "size": 1
                    }
                }
            }
        }
    }
}

Does anyone know how to accomplish this?

Example:

{
  "a":1,
  "b":2,
  "id":4
}
{
  "a":1,
  "b":3,
  "id":1
}
{
  "a":2,
  "b":4,
  "id":3
}

Grouping by "a" and ordering the buckets by "id" (desc) and sorting the top hits on "b" (desc) would give:

{2:{
  "a":2,
  "b":4,
  "id":3
},1:{
  "a":1,
  "b":3,
  "id":1
}}

回答1:


You can do it with the following query. The idea is to show for each parent_uuid bucket the first top hit with the minimum id value and to sort the parent_uuid buckets according the smallest id value as well using a min sub-aggregation.

{
  "aggregations": {
    "toBeOrdered": {
      "terms": {
        "field": "parent_uuid",
        "size": 1000000,
        "order": {
          "topSort": "desc"
        }
      },
      "aggregations": {
        "topAnswer": {
          "top_hits": {
            "size": 1,
            "sort": {
              "b": "desc"
            }
          }
        },
        "topSort": {
          "max": {
            "field": "id"
          }
        }
      }
    }
  }
}

Try it out and report if this works out for you.



来源:https://stackoverflow.com/questions/33305415/elasticsearch-ordering-terms-aggregation-buckets-after-field-in-top-hits-sub-agg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!