ElasticSearch计算按组分组的多个字段

时间:2015-12-10 00:44:56

标签: elasticsearch filter count group-by

我有像

这样的文件
{"domain":"US", "zipcode":"11111", "eventType":"click", "id":"1", "time":100}

{"domain":"US", "zipcode":"22222", "eventType":"sell", "id":"2", "time":200}

{"domain":"US", "zipcode":"22222", "eventType":"click", "id":"3","time":150}

{"domain":"US", "zipcode":"11111", "eventType":"sell", "id":"4","time":350}

{"domain":"US", "zipcode":"33333", "eventType":"sell", "id":"5","time":225}

{"domain":"EU", "zipcode":"44444", "eventType":"click", "id":"5","time":120}

我想通过eventType = sell和125到400之间的时间过滤这些文档,按域分组然后是zipcode并计算每个桶中的文档。所以我的输出就像(过滤器会忽略第一个和最后一个文档)

US,11111,1

美国,22222,1

美国,33333,1

在SQL中,这应该是直截了当的。但是我无法让它在ElasticSearch上运行。有人可以帮帮我吗?

如何编写ElasticSearch查询来完成上述操作?

1 个答案:

答案 0 :(得分:1)

此查询似乎可以执行您想要的操作:

POST /test_index/_search
{
   "size": 0,
   "query": {
      "filtered": {
         "filter": {
            "bool": {
               "must": [
                  {
                     "term": {
                        "eventType": "sell"
                     }
                  },
                  {
                     "range": {
                        "time": {
                           "gte": 125,
                           "lte": 400
                        }
                     }
                  }
               ]
            }
         }
      }
   },
   "aggs": {
      "zipcode_terms": {
         "terms": {
            "field": "zipcode"
         }
      }
   }
}

返回

{
   "took": 8,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 3,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "zipcode_terms": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": "11111",
               "doc_count": 1
            },
            {
               "key": "22222",
               "doc_count": 1
            },
            {
               "key": "33333",
               "doc_count": 1
            }
         ]
      }
   }
}

(请注意,“22222”只有1“卖”,而不是2)。

以下是我用来测试它的一些代码:

http://sense.qbox.io/gist/1c4cb591ab72a6f3ae681df30fe023ddfca4225b

您可能需要查看terms aggregationsbool filterrange filters

编辑:我刚刚意识到我遗漏了域名部分,但是如果你需要的话,也应该直接添加一个桶聚合。