elasticsearch - Elasticsearch - 按最后一个时间戳聚合,加上过滤、排序和分页
问题描述
我有一个 Elasticsearch 索引,其中包含具有以下结构的条目:
{
// id of the entry
"EntryId": integer,
// The timestamp of the entry being processed, usually there are multiple entries with different "ChangeDate" for the same "EntryId"
// formatted as a UTC date, always in the same timezone
"ChangeDate": date
// Other fields
"Field1": integer,
"Field2": text,
...
}
现在我想要实现的是能够查询条目并同时拥有以下所有内容:
- 返回包含所有字段的整个条目的列表
- 通过 max(ChangeDate) 在 EntryId 上聚合,即只应考虑具有相同 EntryId 的所有条目中的最新条目
- 允许过滤任何字段
- 允许根据所选字段(可能不止一个)对结果集进行排序
- 允许对结果集进行分页
以下是我的解决方案,里面有评论。但是,这种方案的局限性在于,top_hits 中的分页默认只允许 100 个 top 结果。虽然我仍然可以通过设置 [index.max_inner_result_window] 来覆盖它。但这仍然是一个硬限制,用户将无法分页到任意结果集的末尾。
我的问题是:
- 就正确性而言,这是一个很好的解决方案,还是这里有一些不明显的 Elasticsearch 警告?
- 是否有其他具有相同或相似功能的首选解决方案?
- 如果我想以自然方式摆脱结果集大小限制,即不由 [index.max_inner_result_window] 强制执行,并允许访问整个结果集,是否有一个好的解决方案?
解决方案:
GET /index-1/_search
{
"size": 0,
// This sorting prepares the correct order for the following "collapse" below, i.e. last ChangeDate goes first
"sort": [{ "ChangeDate": "desc" }],
"query" : {
// This allows filtering on arbitrary fields
"bool": {
"must": [
{"range": {"Field1": {"gte": 30000}}}
]
}},
// This chooses only one entry with the latest ChangeDate among all entries with the same EntryId
"collapse" : {
"field" : "EntryId"
},
"aggs": {
"TopHits": {
"top_hits": {
// This forces sorting of the result set first by Field1 then by EntryId
"sort": [{"Field1": {"order": "asc"}}, {"EntryId": {"order": "asc"}}],
// This is result set pagination
"from": 60,
"size": 10,
// This includes the whole entry in the result source
"_source": { "includes": ["*"]}
}
}
}
}
解决方案
推荐阅读
- spring - 如何将从 Spring 库扫描的组件包含到使用该库的主应用程序中?
- filtering - 我如何将多个部分匹配字符串从行中拉出并在同一行上保持相同的顺序?
- sql - 当我导出 PDF 时,无法识别自定义代码
- python - 如果 Outlook 打开,Python 程序在任务计划程序中运行时不起作用
- azure - 通过 Azure Devops CICD 管道执行简单的 SQL 查询
- java - Java 中大数的 double 与 long
- mysql - .Net Entity Framework with Mysql 8.0.20 需要什么权限?
- npm - Nexus err500 输入输出错误 npm install
- r - 在 RMarkdown 中,为什么 kable 表打印在标题下方?
- c - 在 C 中使用 GTK 构建 GUI,使用基础小部件是否一切皆有可能?或者我应该建立一个定制的?