如何获得elasticsearch中最频繁模式的计数?

时间:2015-05-10 18:41:44

标签: elasticsearch

我希望通过elasticsearch获得十种最常见的搜索模式 示例:

"cgn:4189, dfsdkfldslfs"
"cgn:4210, aezfvdsvgds"
"cgn:4189, fdsmpfjdjs"
"cgn:4195, cvsf"
"cgn:4189, mkpjd"
"cgn:4210, mfsfgkpjd"

我想得到:

4189 : 3
4210 : 2
4195 : 1

我知道如何在mysql或通过awk / sort / head进行此操作...但是elasticsearch我失去了。

1 个答案:

答案 0 :(得分:0)

它的确切工作方式取决于您的分析器,但如果您只使用默认值standard analyzer,则可以使用terms aggregation轻松获得您想要的内容。

作为一个简单的例子,我设置了一个简单的索引:

PUT /test_index
{
   "settings": {
      "number_of_shards": 1
   }
}

然后使用bulk api

为您发布的数据编制索引
POST /test_index/doc/_bulk
{"index":{"_id":1}}
{"msg":"cgn:4189, dfsdkfldslfs"}
{"index":{"_id":2}}
{"msg":"cgn:4210, aezfvdsvgds"}
{"index":{"_id":3}}
{"msg":"cgn:4189, fdsmpfjdjs"}
{"index":{"_id":4}}
{"msg":"cgn:4195, cvsf"}
{"index":{"_id":5}}
{"msg":"cgn:4189, mkpjd"}
{"index":{"_id":6}}
{"msg":"cgn:4210, mfsfgkpjd"}

然后我可以运行一个简单的术语聚合来获取所有术语以及它们发生的频率(默认情况下按术语频率降序排列):

POST /test_index/_search?search_type=count
{
   "aggs": {
      "msg_terms": {
         "terms": {
            "field": "msg"
         }
      }
   }
}

返回:

{
   "took": 4,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 6,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "msg_terms": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": "cgn",
               "doc_count": 6
            },
            {
               "key": "4189",
               "doc_count": 3
            },
            {
               "key": "4210",
               "doc_count": 2
            },
            {
               "key": "4195",
               "doc_count": 1
            },
            {
               "key": "aezfvdsvgds",
               "doc_count": 1
            },
            {
               "key": "cvsf",
               "doc_count": 1
            },
            {
               "key": "dfsdkfldslfs",
               "doc_count": 1
            },
            {
               "key": "fdsmpfjdjs",
               "doc_count": 1
            },
            {
               "key": "mfsfgkpjd",
               "doc_count": 1
            },
            {
               "key": "mkpjd",
               "doc_count": 1
            }
         ]
      }
   }
}

以下是我使用的代码:

http://sense.qbox.io/gist/a827095b675596c4e3d545ce963cde3fae932156