簡體   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