我正在寻找一种解决方案,可以按keyword
字段中的特定值来聚合数据。
以下是数据:
"message" : "status: 123, msg: blablabla",
"message" : "start_at: 20190701, source: location_a",
"message" : "status: 456, msg: blabla",
"message" : "start_at: 20190701, source: location_b",
"message" : "status: 123, msg: blablablabla",
({message
是keyword
字段)
然后,我通过以下方式查询了该索引:
GET my_index/_search
{
"query": {
"match": {
"message": {
"query": "status"
}
}
}
}
然后,我得到的结果如下:
{
"hits" : [
{
"_index" : "2019.07.25",
"_source" : {
"message" : """status: 123, msg: blablabla""",
}
},
{
"_index" : "2019.07.25",
"_source" : {
"message" : """status: 456, msg: blabla""",
}
},
{
"_index" : "2019.07.25",
"_source" : {
"message" : """status: 123, msg: blablablabla""",
}
}
]
}
现在,我希望按status
的值来汇总数据,例如:
{
"aggregations" : {
"status" : {
"buckets" : {
"123" : {
"doc_count" : 250
},
"456" : {
"doc_count" : 248
},
"789" : {
"doc_count" : 2356
}
}
}
}
}
(原始数据中有100多种不同的state
。)
那么,我该如何汇总这些数据?
(ps。我正在使用Elasticsearch 6.5)
答案 0 :(得分:0)
您可以在聚合术语中使用轻松的脚本
GET my_index/_search
{
"size": 0,
"aggs": {
"genres": {
"terms": {
"script": {
"inline": "def field = 'status: '; def msg = doc['message.keyword'].value; def start = msg.indexOf(field); def end = msg.indexOf(',', start); if(start > -1) {return msg.substring(start+field.length(), end)}"
}
}
}
}
}
样本输出:
"aggregations": {
"genres": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "123",
"doc_count": 2
},
{
"key": "456",
"doc_count": 1
}
]
}
}
首先,脚本使用indexOf方法找到status:
的位置,然后使用子字符串方法找到直接的,
这两个索引位置,以提取状态值