How to get a count for each type of an index in elasticsearch? How to get a count for each type of an index in elasticsearch? elasticsearch elasticsearch

How to get a count for each type of an index in elasticsearch?


You can use terms aggregations on the _type field to get this information:

curl "localhost:9200/test-idx/_search?search_type=count" -d '{    "aggs": {        "count_by_type": {            "terms": {                "field": "_type"            }        }    }}'


For Elasticsearch v5.0, search_type=count is removed. The same query from the above answers can be written as follows:

GET  indexname/_search{    "aggs": {        "count_by_type": {            "terms": {                "field": "_type"            }        }    },    "size": 0}

Ref: https://www.elastic.co/guide/en/elasticsearch/reference/5.0/breaking_50_search_changes.html#_literal_search_type_count_literal_removed


The "facets" are deprecated in ES v. 1.5+ However you can use "aggregations", the use and results are quite similar:

curl "localhost:9200/events/_search?search_type=count" -d '{    "aggregations": {        "count_by_type": {            "terms": {                "field": "_type"            }        }    },    "size": 0}'

You'll get something like:

{   "took": 21,   "timed_out": false,   "_shards": {      "total": 10,      "successful": 10,      "failed": 0   },   "hits": {      "total": 150,      "max_score": 0,      "hits": []   },   "aggregations": {      "count_by_type": {         "doc_count_error_upper_bound": 0,         "sum_other_doc_count": 0,         "buckets": [            {               "key": "type1",               "doc_count": 141            },            {               "key": "type2",               "doc_count": 6            },            {               "key": "other_type",               "doc_count": 3            }         ]      }   }}