繁体   English   中英

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

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

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

因此,例如,索引是

/events

而且类型可能是

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

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

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

/ events / _count会给我的地方

/events: 70

编辑

伊莫托夫的答案很棒。 我很难搞清楚如何让它轻松地在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中元素的总数,答案的方面部分似乎缺失了。

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

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

对于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

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

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
            }
         ]
      }
   }
}

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

GET  index/_search
{
    "aggs": {
        "countByType": {
            "terms": {
                "field": "_type"
            }
        }
    },
    "size": 0
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM