如何使用 Elasticsearch 查询获取每个组的最新值? [英] How to get latest values for each group with an Elasticsearch query?

查看:56
本文介绍了如何使用 Elasticsearch 查询获取每个组的最新值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Elasticsearch 上索引了一些文档,看起来像这些示例:

I have some documents indexed on Elasticsearch, looking like these samples:

{'country': 'France', 'collected': '2015-03-12', 'value': 20}
{'country': 'Canada', 'collected': '2015-03-12', 'value': 21}
{'country': 'Brazil', 'collected': '2015-03-12', 'value': 33}
{'country': 'France', 'collected': '2015-02-01', 'value': 10}
{'country': 'Canada', 'collected': '2015-02-01', 'value': 11}
{'country': 'Mexico', 'collected': '2015-02-01', 'value': 9}
...

我想构建一个查询,每个国家/地区获取一个结果,仅获取具有 max(collected) 的结果.

I want to build a query that gets one result per country, getting only the ones with max(collected).

因此,对于上面显示的示例,结果将类似于:

So, for the examples shown above, the results would be something like:

{'country': 'France', 'collected': '2015-03-12', 'value': 20}
{'country': 'Canada', 'collected': '2015-03-12', 'value': 21}
{'country': 'Brazil', 'collected': '2015-03-12', 'value': 33}
{'country': 'Mexico', 'collected': '2015-02-01', 'value': 9}

我意识到我需要对 country 进行聚合,但我无法理解如何限制 max(collected) 上的结果.

I realized I need to do aggregation on country, but I'm failing to understand how to limit the results on max(collected).

有什么想法吗?

推荐答案

您可以使用 top_hitscountry 字段上分组的聚合,每组返回 1 个文档,并按收集日期降序:

You can use a top_hits aggregation that groups on the country field, returns 1 doc per group, and orders the docs by the collected date descending:

POST /test/_search?search_type=count
{
    "aggs": {
        "group": {
            "terms": {
                "field": "country"
            },
            "aggs": {
                "group_docs": {
                    "top_hits": {
                        "size": 1,
                        "sort": [
                            {
                                "collected": {
                                    "order": "desc"
                                }
                            }
                        ]
                    }
                }
            }
        }
    }
}

这篇关于如何使用 Elasticsearch 查询获取每个组的最新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆