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

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

问题描述

  {'country':'法国','收集':'2015-03-12','value':20} 
{'country':'加拿大','收集':'2015-03-12','value':21}
{'国家':'巴西','收集':'2015-03-12','价值':33}
{'国家':'法国','收集':'2015-02 -01','value':10}
{'country':'加拿大'''收集':'2015-02-01','value':11}
{'country' 墨西哥,收集:2015-02-01,值:9}
...

我想建立一个查询,每个国家/地区只得到一个结果,只有 max(已收集)



所以,对于上面的例子,结果将是这样的:

  {'国家':'法国','收集':'2015-03-12','值':20} 
{'国家'加拿大','收集':'2015-03-12','价值':21}
{'国家':'巴西','收集':'2015-03-12' 33}
{'country':'墨西哥','收集':'2015-02-01','value':9}

我意识到我需要在 country 上进行聚合,但是我无法理解如何限制<$



任何想法?

解决方案

您可以使用国家/地区字段中分组的 c> 聚合,返回每个组1个文档和订单文档按收集日期递减:

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


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

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}

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

Any ideas?

解决方案

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天全站免登陆