我有一个索引,想要计算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中元素的总数,答案的方面部分似乎缺失了。
答案 0 :(得分:36)
您可以在_type
字段上使用字词聚合来获取此信息:
curl "localhost:9200/test-idx/_search?search_type=count" -d '{
"aggs": {
"count_by_type": {
"terms": {
"field": "_type"
}
}
}
}'
答案 1 :(得分:18)
对于Elasticsearch v5.0,将删除 search_type = count 。上述答案中的相同查询可写如下:
{{1}}
答案 2 :(得分:8)
The "facets" are deprecated in ES v. 1.5+ However you can use "aggregations", the use and results are quite similar:
curl "localhost:9200/events/_search?search_type=count" -d '{
"aggregations": {
"count_by_type": {
"terms": {
"field": "_type"
}
}
},
"size": 0
}'
You'll get something like:
{
"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
}
]
}
}
}
答案 3 :(得分:3)
@Askshay和@Roberto的答案突出了另一个重要方面。将大小设置为0非常重要,尤其是在低带宽使用情况下(例如在移动网络中)。它减少了数据有效负载大小,并且在文档大小很大时会产生巨大差异。注意" size":0
GET index/_search
{
"aggs": {
"countByType": {
"terms": {
"field": "_type"
}
}
},
"size": 0
}