Search code examples
elasticsearch

Elasticsearch: How count the total number of terms aggregated for each field in the same request


I am getting an aggregated list of plays in the data with this request

GET /shakespeare/_search
{
  "aggs": {
    "plays": {
      "terms": { "field": "play_name",
      "order": { "_key": "asc" },
      "size": 200  
      }
    }
  }

and the total number of plays with this request

GET /shakespeare/_search
{
  "aggs": {
    "terms_count": {
      "cardinality": { "field": "play_name"}
    }
  }
}

Is there a way to get the total number of terms for each of the fields in one request?

GET /shakespeare/_mapping

gives

{
  "shakespeare": {
    "mappings": {
      "_meta": {
        "created_by": "file-data-visualizer"
      },
      "properties": {
        "index": {
          "properties": {
            "_id": {
              "type": "long"
            },
            "_index": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            }
          }
        },
        "line_id": {
          "type": "long"
        },
        "line_number": {
          "type": "keyword"
        },
        "play_name": {
          "type": "keyword"
        },
        "speaker": {
          "type": "keyword"
        },
        "speech_number": {
          "type": "keyword"
        },
        "text_entry": {
          "type": "text"
        },
        "type": {
          "type": "keyword"
        }
      }
    }
  }
}

For example how can I get all these 3 fields: speaker, line_number and play_name in the same request.


Solution

  • You can perform multiple aggregation in the same _search request.

    GET /shakespeare/_search
    {
      "size": 0,
      "aggs": {
        "plays": {
          "terms": {
            "field": "play_name"
          }
        },
        "terms_count": {
          "cardinality": {
            "field": "play_name"
          }
        }
      }
    }
    

      #response
      "aggregations": {
        "terms_count": {
          "value": 2
        },
        "plays": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": "Pericles",
              "doc_count": 3
            },
            {
              "key": "Henry IV",
              "doc_count": 1
            }
          ]
        }
      }
    

    enter image description here