Elasticsearch:如何返回字段中具有最高值的所有文档?

标签 elasticsearch

我是 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

提前致谢!

最佳答案

您可以像这样组合termstop_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/

相关文章:

python - Elasticsearch Shape 查询以从嵌套 JSON 中查找边界多边形和背景颜色(Google OCR 响应)

elasticsearch - NEST(2.x)带有分数间隔值的日期直方图聚合

sql - 高效计算 SQL 中的重要术语

elasticsearch - 如何杀死elasticsearch集群上搜索请求的线程?有一些API可以做到这一点吗?

mongodb - Elasticsearch River(mongodb),建模架构

Elasticsearch NEST DefaultMapping供使用

database - 将旧数据从 postgres 导入到 elasticsearch

python - 自定义 View 在带有 Elastic Search 的 Django Haystack 中不显示结果

spring - 我应该在Spring Batch流程中的哪里索引项目?

elasticsearch - ElasticSearch计算按以下字段分组的多个字段