elasticsearch - 从弹性搜索上的子聚合访问嵌套变量
问题描述
我有一个包含如下文档的索引:
{
"id": 1,
"timeline": [{
"amount": {
"mpe": 30,
"drawn": 20
},
"interval": {
"gte": "2020-03-01",
"lte": "2020-04-01"
}
}, {
"amount": {
"mpe": 40,
"drawn": 10
},
"interval": {
"gte": "2020-04-01",
"lte": "2020-06-01"
}
}]
}
然后我有以下查询,它产生原始间隔中值的时间分段总和:
{
"aggs": {
"cp-timeline": {
"nested": {
"path": "timeline"
},
"aggs": {
"mpes": {
"date_histogram": {
"field": "timeline.interval",
"calendar_interval": "day"
},
"aggs": {
"sum_mpe": {
"sum": {
"field": "timeline.amount.mpe"
}
},
"sum_drawn": {
"sum": {
"field": "timeline.amount.drawn"
}
}
}
}
}
}
}
}
上面的工作就像一个魅力,每天产生正确的总和。现在我想改进它,以便我可以动态地将值乘以可能在查询执行之间变化的给定数字,尽管为简单起见,我将只使用固定数字 2。我尝试了以下方法:
{
"aggs": {
"cp-timeline": {
"nested": {
"path": "timeline"
},
"aggs": {
"mpes": {
"date_histogram": {
"field": "timeline.interval",
"calendar_interval": "day"
},
"aggs": {
"sum_mpe": {
"sum": {
"script": "timeline.amount.mpe * 2"
}
},
"sum_drawn": {
"sum": {
"script": "timeline.amount.drawn * 2"
}
}
}
}
}
}
}
}
但我收到以下错误:
{
"reason": {
"type": "script_exception",
"reason": "compile error",
"script_stack": [
"timeline.amount.mpe * 2",
"^---- HERE"
],
"script": "timeline.amount.mpe * 2",
"lang": "painless",
"position": {
"offset": 0,
"start": 0,
"end": 23
},
"caused_by": {
"type": "illegal_argument_exception",
"reason": "Variable [timeline] is not defined."
}
}
}
有没有办法使上面声明的嵌套变量在脚本中可用?
解决方案
此链接说明如何通过脚本访问字段。请注意,您只能将其用于分析的字段,即text
类型。
以下内容应该有所帮助:
POST <your_index_name>/_search
{
"size": 0,
"aggs": {
"cp-timeline": {
"nested": {
"path": "timeline"
},
"aggs": {
"mpes": {
"date_histogram": {
"field": "timeline.interval.gte",
"calendar_interval": "day",
"min_doc_count": 1 <---- Note this
},
"aggs": {
"sum_mpe": {
"sum": {
"script": "doc['timeline.amount.mpe'].value * 2" <---- Note this
}
},
"sum_drawn": {
"sum": {
"script": "doc['timeline.amount.drawn'].value * 2" <---- Note this
}
}
}
}
}
}
}
}
另请注意,我已经使用了min_doc_count
这样您的直方图只会显示有效日期。
推荐阅读
- c# - 如何以 HTML 格式呈现从数据库返回的 SQL Server 文件流 .jpg 图像
- java - 按钮适用于android中的第二次点击
- python - 使用评估生成器的准确度为 0%,但在使用相同数据进行训练期间的准确度为 75%——这是怎么回事?
- arrays - 在 PowerShell 中的数组上使用 Invoke-WebRequest
- python - 尝试检索类属性时出错。
- angular - Angular 5 InMemoryDbService 集合不起作用
- linux - 使用 tr 从命令行参数中修剪换行符被忽略
- c# - SSL 连接在没有客户端身份验证的情况下失败
- keras - ImportError:无法导入名称“图表”
- regex - 在熊猫数据框中添加“id”