首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Elasticsearch DSL查询

Elasticsearch DSL查询
EN

Stack Overflow用户
提问于 2021-08-26 20:43:38
回答 1查看 30关注 0票数 0
代码语言:javascript
运行
复制
{
    "name" : "Danny",
    "id" : "123",
    "lastProfileUpdateTime" : "2021-06-26T20:08:25.089Z"
},
{
    "name" : "Harry",
    "id" : "124",
    "lastProfileUpdateTime" : "2021-04-12T20:08:25.089Z"
},
{
    "name" : "Danny Brown",
    "id" : "123",
    "lastProfileUpdateTime" : "2021-07-26T20:08:25.089Z"
},
{
    "name" : "Danny Smith",
    "id" : "123",
    "lastProfileUpdateTime" : "2021-08-26T20:08:25.089Z"
}

我有一个用例,我需要找出一个特定的id是否已经更新,并过滤掉最新的配置文件。在上述情况下,因为id:123已经更新了配置文件。因此,预期结果应该是:

代码语言:javascript
运行
复制
{
    "name" : "Danny Smith",
    "id" : "123",
    "lastProfileUpdateTime" : "2021-08-26T20:08:25.089Z"
} 

如果id有多个条目,请选择具有最新lastProfileUpdateTime的条目。

EN

回答 1

Stack Overflow用户

发布于 2021-08-28 05:32:01

这可以使用以下命令来完成

  1. Terms aggregation:按计数分组以获取id,其中"id"
  2. Bucket selector:> 1
  3. Top_hits:以获取给定id的最新文档

查询

代码语言:javascript
运行
复制
{
  "size": 0,
  "aggs": {
    "Updated_docs": {
      "terms": {
        "field": "id.keyword",
        "size": 10
      },
      "aggs": {
        "filter_count_more_than_one": {
          "bucket_selector": {
            "buckets_path": {
              "count": "_count"
            },
            "script": "params.count>1"
          }
        },
        "latest_document": {
          "top_hits": {
            "size": 1,
            "sort": [
              {
                "lastProfileUpdateTime": "desc"
              }
            ]
          }
        }
      }
    }
  }
}

结果

代码语言:javascript
运行
复制
 "aggregations" : {
    "Updated_docs" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "123",
          "doc_count" : 3,
          "latest_document" : {
            "hits" : {
              "total" : {
                "value" : 3,
                "relation" : "eq"
              },
              "max_score" : null,
              "hits" : [
                {
                  "_index" : "index4",
                  "_type" : "_doc",
                  "_id" : "huE1i3sBZ5_aIkj8cvpR",
                  "_score" : null,
                  "_source" : {
                    "name" : "Danny Smith",
                    "id" : "123",
                    "lastProfileUpdateTime" : "2021-08-26T20:08:25.089Z"
                  },
                  "sort" : [
                    1630008505089
                  ]
                }
              ]
            }
          }
        }
      ]
    }
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68945100

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档