顶级命中的ElasticSearch聚合

时间:2016-07-05 04:55:41

标签: elasticsearch

我的数据如下:

{"action":"CREATE","docs":1,"date":"2016 Jun 26 12:00:12","userid":"1234"}
{"action":"REPLACE","docs":2,"date":"2016 Jun 27 12:00:12","userid":"1234"}
{"action":"REPLACE","docs":1,"date":"2016 Jun 27 13:00:12","userid":"1234"}
{"action":"CREATE","docs":1,"date":"2016 Jun 28 12:00:12","userid":"3431"}
{"action":"REPLACE","docs":2,"date":"2016 Jun 28 13:00:12","userid":"3431"}
{"action":"CREATE","docs":1,"date":"2016 Jun 29 12:00:12","userid":"9999"}

要按日期(降序)获取每个唯一用户订单的记录,我使用了如下所示的热门点击:

"aggs": {
            "user_bucket": {
                "terms": {
                    "field": "userid"
                },
                "aggs": {
                    "user_latest_count": {
                        "top_hits": {
                            "size": 1,
                            "sort": [
                                {
                                    "data": {
                                        "order": "desc"
                                    }
                                }
                            ],
                            "_source": {
                                "include": [
                                    "docs"
                                ]
                            }
                        }
                    }
                }
            }
        }

以上查询的结果如下:

{"action":"REPLACE","docs":1,"date":"2016 Jun 27 13:00:12","userid":"1234"}
{"action":"REPLACE","docs":2,"date":"2016 Jun 28 13:00:12","userid":"3431"}
{"action":"CREATE","docs":1,"date":"2016 Jun 29 12:00:12","userid":"9999"}

现在,我想进一步聚合,以便结果如下:

{"sum_of_different_buckets": 4}

但不确定如何 SUM 字段" docs "从上面得到的结果中得出的值。

2 个答案:

答案 0 :(得分:0)

您还可以在聚合中任意嵌套聚合,以从数据中提取所需的汇总数据。可能低于样本作品。

@IBAction func segmentedControlTapped(sender: AnyObject) {
    if segmentedControl.selectedSegmentIndex == 1 {
        self.viewUIPickerView.viewWithTag(10)?.hidden = false
        self.viewUIPickerView2.viewWithTag(11)?.hidden = true
    }else {
        self.viewUIPickerView2.viewWithTag(11)?.hidden = false
        self.viewUIPickerView.viewWithTag(10)?.hidden = true
    }

    self.tabBarController!.tabBar.hidden = true

}

答案 1 :(得分:0)

您可以在 top_hit 的平行级别上具有其他聚合,但是在以下 top_hit 中不能具有任何 sub_aggregation 。 elasticsearch不支持它。 here is the link to github issue

但是,如果您希望总和处于同一水平,则可以使用以下方法。

"aggs": {
    "top_hits_agg": {
        "top_hits": {
            "size": 10,
            "_source": {
              "includes": ["docs"]
            }
        }
    },
    "sum_agg": {
        "sum": {
            "field": "docs"
        }
    }
}