Search code examples
elasticsearchelasticsearch-aggregationelasticsearch-dsl

How to add multiple Fields in the Bucket sort Elastic search query


Below is the query. Inside this query, I need to add one more field which is category.keyword. I am finding it difficult to add an additional field. Please modify my query and add the category keyword field also inside the Query.

My requirement is to show the list of questions and list of categories with the count.

{
  "size": 0,
  "aggs": {
    "genres": {
      "terms": {
        "field": "question.keyword",
        "order": {
          "_count": "desc"
        }
      },
      "aggs": {
        "bucket_truncate": {
          "bucket_sort": {
            "from": 0,
            "size": 10
          }
        }
      }
    }
  }
}

Index Mapping details

  "mapping": {
    "properties": {
      "answer": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "category": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "id": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "question": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "relavence_score": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "source": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
}
      },
      "timestamp": {
        "type": "long"
      },
      "id": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      }
    }
  }
}


Solution

  • You can have multiple aggregations at the same level, in your case bucket_truncate and categories:

    {
      "size": 0,
      "aggs": {
        "questions": {
          "terms": {
            "field": "question.keyword",
            "order": {
              "_count": "desc"
            }
          },
          "aggs": {
            "categories": {
              "terms": {
                "field": "category.keyword",
                "order": {
                  "_count": "desc"
                }
              }
            },
            "bucket_truncate": {
              "bucket_sort": {
                "from": 0,
                "size": 10
              }
            }
          }
        }
      }
    }