2013-07-09 54 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 
} 
相关问题