20

我有一个索引,并希望在 elasticsearch 中获取一个特定索引的每种类型的条目计数,但可能不提前知道类型。

因此,例如,索引是

/events

类型可能是

/events/type1
/events/type2
...
/events/typeN

而且我想查询索引并说“给我索引事件下每种类型的计数”,所以结果集可能像

/events/type1 : 40
/events/type2: 20
/events/typeN: 10

/events/_count 会给我

/events: 70

编辑

imotov 的回答很棒。不过,我很难弄清楚如何让它在 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);
}
)}'

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

4

4 回答 4

39

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

curl "localhost:9200/test-idx/_search?search_type=count" -d '{
    "aggs": {
        "count_by_type": {
            "terms": {
                "field": "_type"
            }
        }
    }
}'
于 2013-07-09T21:01:14.647 回答
21

对于 Elasticsearch v5.0,search_type=count被移除。来自上述答案的相同查询可以写成如下:

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

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

于 2016-11-04T22:47:30.507 回答
8

“方面”在 ES v. 1.5+ 中已弃用但是您可以使用“聚合”,使用和结果非常相似:

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

你会得到类似的东西:

{
   "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
            }
         ]
      }
   }
}
于 2015-07-28T16:11:19.730 回答
3

@Askshay 和 @Roberto 的回答突出了另一个重要方面。将大小设置为 0 非常重要,尤其是在低带宽用例中(例如在移动网络中)。它减少了数据有效负载的大小,并且当文档大小很大时会产生巨大的差异。注意“大小”:0

GET  index/_search
{
    "aggs": {
        "countByType": {
            "terms": {
                "field": "_type"
            }
        }
    },
    "size": 0
}
于 2016-11-16T14:29:45.620 回答