【问题标题】:Elasticsearch: How to return all documents that have the highest value in a field?Elasticsearch:如何返回字段中具有最高值的所有文档?
【发布时间】:2018-03-06 07:37:33
【问题描述】:

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

提前致谢!

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    你可以像这样组合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

    【讨论】:

    • 应该被标记为可接受的值。非常感谢。作为旁注,我不能在 aggs 大小中放置超过 100,9000 返回错误 ===> 热门点击结果窗口太大,热门点击聚合器 [latest_results] 的来自 + 大小必须小于或等于到:[100] 但为 [9000]。可以通过更改 [index.max_inner_result_window] 索引级别设置来设置此限制。显然这与索引配置有关
    猜你喜欢
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多