我是 Elasticsearch 的新手,目前我在解决一个相当基本的问题时遇到了一些困难。假设我有以下映射:
PUT /myindex/_mappings/people
{
"properties": {
"name": {"type": "keyword"},
"age" : {"type": "integer"},
}
}
带有以下文件:
{"name": "Bob", "age": 20},
{"name": "Ben", "age": 25},
{"name": "Eli", "age": 30},
{"name": "Eva", "age": 20},
{"name": "Jan", "age": 21},
{"name": "Jim", "age": 20},
{"name": "Lea", "age": 30},
如何创建单个查询来返回索引中年龄最大的所有人员?换句话说,我期待 Eli 和 Lea 回来,因为他们都 30 岁了,比其他人都大。
我正在为 javascript 使用 Elasticsearch API 6.0.0(我的应用程序是用 nodejs 编写的)。现在,我的解决方法是对数据库执行 2 个请求。首先是聚合最大年龄(应该返回 30),然后使用这个最大年龄执行另一个请求:
GET /myindex/people/_search
{
"aggs": {
"max_age": {"max": {"field": "age"}}
}
}
GET /myindex/people/_search
{
"query": {"term": {"age": <max_age>}} // where <max_age> should be 30
}
显然,这是非常低效的。你能帮我制定一个查询来完成所有这些吗?
困难的是我事先不知道有多少文档具有最高值,这意味着我不能使用此处提到的“大小”方法“Single query to find document with largest value for some field”
提前致谢!
最佳答案
您可以像这样组合terms
和top_hits
聚合
GET /myindex/people/_search
{
"size": 0,
"aggs": {
"group_by_age": {
"terms": {
"field": "age",
"order": {
"_term": "desc"
},
"size": 1
},
"aggs": {
"oldest_people": {
"top_hits": {
"from": 0,
"size": 9000
}
}
}
}
}
}
注意 "order": { "_term": "desc"}
和 "size": 1
只返回来自 terms 的最大年龄的桶
聚合。然后我们只列出前 9000 个(或任意数量)具有 top_hits
的文档。
关于Elasticsearch:如何返回字段中具有最高值的所有文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49125624/