2013-07-09 55 views
15

我有一個索引,並希望獲得elasticsearch中每個特定索引類型條目的計數,但可能不會提前知道類型。如何獲得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元素的總數,答案的方面部分似乎缺少。

回答

34

您可以使用在_type領域方面的聚合得到這個信息:

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

謝謝!這肯定是有道理的。我似乎無法通過JavaScript/Ajax調用來調用我的ES,但是...您有關於如何做到這一點的提示嗎?現在,我有: $ .ajax({\t type:'GET', \t url:'http:// localhost:9200/events/_search?SEARCH_TYPE =計數」, \t數據: '{ 「刻面」:{ 「count_by_type」:{ 「術語」:{ 「字段」: 「_type」}}}}', \t成功:功能(文本){ \t \t console.log(text); \t}, – cdietschrun

+0

編輯。問題似乎需要發佈該請求,現在我瞭解得更多。 – cdietschrun

+1

某些HTTP客戶端無法通過GET請求發送請求正文。所以,有時需要用'POST'替換命令。 – imotov

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

答案和@Roberto突出的另一個重要方面,從上面的回答同樣的查詢可以按如下方式寫入。將大小設置爲0非常重要,特別是在低帶寬使用情況下(例如在移動網絡中)。它減少了數據有效負載的大小,並且在文檔大小很大時會產生巨大的差異。注意「大小」:0

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