请教 ES 怎么实现如下聚合查询: 按某关键字分组,每个分组找到最近的一条记录,筛选这条"最近记录"中状态字段为"特定状态"

101 天前
 chana71

原始数据类似

[
  {
  "doc_key": 'a',
  "startsAt": '2024 年 1 月 29 日',
  "status": 'a'
  },
  {
  "doc_key": 'a',
  "startsAt": '2024 年 1 月 30 日',
  "status": 'b'
  }
]

对上面样例 需要返回 doc_key=a, status=b的记录。

通过翻文档目前我实现的

{
  "aggs": {
    "unique_doc": {
      "terms": {
        "field": "doc_key", // 每个 doc_key 有多条记录
      }
    },
    "aggs": {
        "latest": {
          "top_hits": {
            "size": 1,
            "sort": [
              {
                "@timestamp": {
                  "order": "desc"
                }
              }
            ]
          }
        },
        "pagination": {
          "bucket_sort": {
            "size": 10,
            "from": 0
          }
        } 
      }
  }
}

问题: 没有实现最后一步状态过滤。 理想是在 top_hits 中能有个 filter 过滤status字段,然后结合bucket selector 过滤 hit count != 0 的桶。
请教各位大佬该怎么做?

836 次点击
所在节点    Elasticsearch
3 条回复
chana71
101 天前
akinoowari
101 天前
这种单字段的,直接 collapse a 然后查 status=b
ijyuqi
100 天前
按排序获取分组最新的一条数据
{
"aggs": {
"group_by_category": {
"terms": {
"field": "doc_key",
"size": 10
},
"aggs": {
"top_records": {
"top_hits": {
"sort": [
{
"doc_key": {
"order": "desc"
}
},
{
"startsAt": {
"order": "desc"
}
}
],
"size": 1
}
}
}
}
}
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1012512

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX