Elasticsearch - 聚合脚本字段

11

我想创建一个脚本字段,计算两个时间戳之间的时间差,然后在该脚本字段上进行平均聚合 (avg)。

我首先尝试了:

{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "and": [
               {
                  "exists": {
                     "field": "time.new_time"
                  }
               },
               {
                  "exists": {
                     "field": "time.first_alert_time"
                  }
               }
            ]
         }
      }
   },
   "script_fields": {
      "timedifference": {
         "script": "doc['time.new_time'].value - doc['time.first_alert_time'].value"
      }
   },
   "aggs": {
      "avg_timedifference": {
         "avg": {
            "field" : "timedifference"
         }
      }
   }
}

这导致聚合平均值 avg_timedifference 下出现了 null 值。

然后我尝试了:

{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "and": [
               {
                  "exists": {
                     "field": "time.new_time"
                  }
               },
               {
                  "exists": {
                     "field": "time.first_alert_time"
                  }
               }
            ]
         }
      }
   },
   "script_fields": {
      "timedifference": {
         "script": "doc['time.new_time'].value - doc['time.first_alert_time'].value"
      }
   },
   "aggs": {
      "avg_timedifference": {
         "avg": {
            "script" : "doc['timedifference'].value"
         }
      }
   }
}

发生错误:映射中未找到[timedifference]字段

1个回答

31

将脚本简单地移动到集合中,如何?

{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "and": [
               {
                  "exists": {
                     "field": "time.new_time"
                  }
               },
               {
                  "exists": {
                     "field": "time.first_alert_time"
                  }
               }
            ]
         }
      }
   },
   "aggs": {
      "avg_timedifference": {
         "avg": {
            "script" : "Math.ceil(doc['time.new_time'].value - doc['time.first_alert_time'].value)"
         }
      }
   }
}

这个很好用,谢谢。这会产生一个浮点数值,有没有一种方法可以运行另一个脚本来四舍五入数字? - Or Weinberger
我已经更新了我的答案,你可以根据需要使用任何 Math 函数,例如 Math.ceil()Math.floor()Math.round() - Val
嗯,当然,因为avg聚合的结果很可能不是整数。你能在客户端处理它吗? - Val
如果没有其他办法,那么是的,我会在客户端处理它。感谢您的所有帮助。 - Or Weinberger
@Lubbo 随时提出新问题,说明您的具体需求。 - Val
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接