Home > Software design >  elastic search sort after aggregation
elastic search sort after aggregation

Time:06-30

I have an elastic search query showing distinct value for [Have CVID], for each CONTACT_ID, and I want to sort by [Have CVID] count after aggregation. Where can I add the sort by here?

POST /dashboard/_search?size=0
{
  "query": {
    "bool": {
      "must_not": [
       {
          "match": {
            "Have CVID": ""
          }
        }
      ]
    }
  },
  "aggs": {
        "CVID": {
          "terms": {
            "field": "CONTACT_ID.keyword"
          },
      "aggs": {
        "type_count": {
          "cardinality": {
            "field": "Have CVID.keyword"
          }
        }
      }
   }}
}

CodePudding user response:

You can add order to your terms aggregation and specify a sub-aggregation to order by, like this:

POST /dashboard/_search?size=0
{
  "query": {
    "bool": {
      "must_not": [{
        "match": {
          "Have CVID": ""
        }
      }]
    }
  },
  "aggs": {
    "CVID": {
      "terms": {
        "field": "CONTACT_ID.keyword",
        "order": {
          "type_count": "desc"
        }
      },
      "aggs": {
        "type_count": {
          "cardinality": {
            "field": "Have CVID.keyword"
          }
        }
      }
    }
  }
}

ElasticSearch documentation

  • Related