簡體   English   中英

如何在Elasticsearch中按特定值聚合關鍵字字段

[英]How to aggregate keyword field by a specific value in elasticsearch

我正在尋找一種解決方案,以按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)

您可以在術語聚合中使用輕松的腳本

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

首先,腳本找到status:的位置status:使用indexOf方法,然后找到立即數,這兩個索引位置用於使用子字符串方法提取狀態值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM