Elasticsearch - 聚合脚本字段

时间:2015-06-01 07:25:30

标签: elasticsearch

我正在尝试创建一个脚本字段,用于计算两个时间戳之间的时差,然后在该脚本字段上聚合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"
         }
      }
   }
}

在聚合的平均值null下产生了avg_timedifference值。

然后我尝试了:

{
   "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 个答案:

答案 0 :(得分:16)

如何简单地将脚本移动到聚合?

{
   "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)"
         }
      }
   }
}