Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

and this is giving me number of products in each category. But I have additional condition. I need to get number of products in each category which are not sold already, so I need to perform filter on terms somehow.

Is there some elegant way of doing this using aggregation framework, or I need to write filtered query?

Thank you

You can merge between Terms Aggregation and Filter Aggregation , and this is how it should look: (tested)

    aggs: {
      categories: {            
        filter: {term: {sold: true}},
        aggs: {
          names: {
            terms: {field: 'category'}

You can add also more conditions to the filter, I hope this helps.

We can use bool filter to AND all terms, eg. "filter": { "bool" : { "must" : [ {"term" : { "isActive" : "1" } }, {"term" : { "isPrivate" : "0" } }, {"term" : { "isOwner" : "1" } } ] } } – Melwyn Jensen Oct 24, 2019 at 11:38

Just to add to the other answer, you can also use a nested query. This is similar to what I had to do. I'm using Elasticsearch 5.2.

From the docs, here is the basic syntax:

"aggregations" : {
    "<aggregation_name>" : {
        "<aggregation_type>" : {
            <aggregation_body>
        [,"aggregations" : { [<sub_aggregation>]+ } ]?
    [,"<aggregation_name_2>" : { ... } ]*

This is how I implemented it:

GET <path> core_data/_search
  "aggs": {
    "NAME": {
      "nested": {
        "path": "ATTRIBUTES"
      "aggs": {
        "NAME": {
          "filter": {
            "term": {
              "ATTRIBUTES.ATTR_TYPE": "EDUCATION_DEGREE"
          "aggs": {
            "NAME": {
              "terms": {
                "field": "ATTRIBUTES.DESCRIPTION",
                "size": 100

This filtered the data down to one bucket, which is what I needed.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.