如何计算elasticsearch中每种索引的计数?

cdi*_*run 18 javascript api count elasticsearch

我有一个索引,想要计算elasticsearch中每个类型的一个特定索引中的条目,但可能不会提前知道类型.

因此,例如,索引是

/events
Run Code Online (Sandbox Code Playgroud)

而且类型可能是

/events/type1
/events/type2
...
/events/typeN
Run Code Online (Sandbox Code Playgroud)

我想查询索引并说"给我索引事件下的每个类型的计数",所以可能结果集像

/events/type1 : 40
/events/type2: 20
/events/typeN: 10
Run Code Online (Sandbox Code Playgroud)

/ events/_count会给我的地方

/events: 70
Run Code Online (Sandbox Code Playgroud)

编辑:

伊莫托夫的答案很棒.我很难搞清楚如何让它轻松地在JavaScript/Ajax中运行.我现在有类似的东西:

$.ajax({
type: 'GET',
url: 'http://localhost:9200/events/_search?search_type=count',
data: '{ "facets" : { "count_by_type" : { "terms" : { "field": "_type" }}}}',
success: function(text) {
    console.log(text);
}
)}'
Run Code Online (Sandbox Code Playgroud)

但是我只获得ES中元素的总数,答案的方面部分似乎缺失了.

imo*_*tov 38

您可以在_type字段上使用术语聚合来获取此信息:

curl "localhost:9200/test-idx/_search?search_type=count" -d '{
    "aggs": {
        "count_by_type": {
            "terms": {
                "field": "_type"
            }
        }
    }
}'
Run Code Online (Sandbox Code Playgroud)

  • 在lastes版本中,警告方面被低估了,使用"aggs"代替 (2认同)

Aks*_*awe 18

对于Elasticsearch v5.0,将删除search_type = count.上述答案中的相同查询可写如下:

GET  indexname/_search
{
    "aggs": {
        "count_by_type": {
            "terms": {
                "field": "_type"
            }
        }
    },
    "size": 0
}
Run Code Online (Sandbox Code Playgroud)

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


Rob*_*rto 8

ES v.1.5 +中不推荐使用"facets".但是,您可以使用"聚合",使用和结果非常相似:

curl "localhost:9200/events/_search?search_type=count" -d '{
    "aggregations": {
        "count_by_type": {
            "terms": {
                "field": "_type"
            }
        }
    },
    "size": 0
}'
Run Code Online (Sandbox Code Playgroud)

你会得到类似的东西:

{
   "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
            }
         ]
      }
   }
}
Run Code Online (Sandbox Code Playgroud)