Ordering term aggregation buckets by sub-aggregrat

2019-08-06 10:34发布

I have two questions about the query seen on this capture:

  1. How do I order by value in the sum_category field in the results? I use respsize again in the query but it's not correct as you can see below.

  2. Even if I make only an aggregration, why do all the documents come with the result? I mean, if I make a group by query in SQL it retrieves only grouped data, but Elasticsearch retrieves all documents as if I made a normal search query. How do I skip them?

enter image description here

1条回答
干净又极端
2楼-- · 2019-08-06 10:56

Try this:

{
    "query" : {
        "match_all" : {}
    },
    "size" : 0,
    "aggs" : {
        "categories" : {
            "terms" : {
                "field" : "category",
                "size" : 999999,
                "order" : {
                    "sum_category" : "desc"
                }
            },
            "aggs" : {
                "sum_category" : {
                    "sum" : {
                        "field" : "respsize"
                    }
                }
            }
        }
    }
}

1). See the note in (2) for what your sort is doing. As for ordering the categories by the value of sum_category, see the order portion. There appears to be an old and closed issue related to that https://github.com/elastic/elasticsearch/issues/4643 but it worked fine for me with v1.5.2 of Elasticsearch.

2). Although you do not have that match_all query, I think that's probably what you are getting results for. And so the sort your specified is actually getting applied to those results. To not get these back, I just have size: 0 portion.

Do you want buckets for all the categories? I noticed you do not have size specified for the main aggregation. That's the size: 999999 portion.

查看更多
登录 后发表回答