Search code examples
elasticsearchkibanaelasticsearch-aggregation

Aggregate by multiple fields and Top 10 questions and answers count in ElasticSearcch


When we execute the records for the few records only questions is coming and it is not showing up the answer against each question In the database we have answers for all the questions. Please let me know the query to get the both questions and answers for top 10 records. Below is the error.

GET logstash-sdc-questionrecords/_search?q=source:website_portal

{
  "aggs": {
    "genres": {
      "terms": {
        "field": "question.keyword",
        "order": {
          "_count": "desc"
        },
        "size": 10
      },
      "aggs": {
        "genres": {
          "terms": {
            "field": "answer.keyword",
            "order": {
              "_count": "desc"
            },
            "size": 10
          }
        }
      }
    }
  }
}

enter image description here


Solution

  • What I understand from your question is that you need to show top 10 questions with their answers, in order to achieve that you need to use the sub-aggregation and top-hits will solve your use-case, while currently you are using two different top level terms aggregation.

    Your search query should look like below

    {
      "aggs": {
        "genres": {
          "terms": {
            "field": "question.keyword",
            "size": 10
          },
          "aggs": {
            "top_answer_hits": {
              "top_hits": {
                "size": 1,
                "_source": {
                  "includes": [
                    "answer"
                  ]
                }
              }
            }
          }
        }
      }
    }