不使用动态脚本查询

Query without using dynamic scripting

我有以下当前使用动态脚本的查询。从那以后,我发现我的主机不支持这个,因为它具有更广泛的安全隐患。我将如何重写此脚本以使其不使用动态脚本?

{
  "size": 0,
  "aggs": {
    "filtered_cells": {
      "filter": {
        "geo_bounding_box": {
          "loc": {
            "top_left": "58.645976, -13.515625",
            "bottom_right": "50.524473, 2.436523"
          }
        }
      },
      "aggs": {
        "cells": {
          "geohash_grid": {
            "field": "loc",
            "precision": 2
          },
          "aggs": {
            "center_lat": {
              "avg": {
                "script": "doc['loc'].lat"
              }
            },
            "center_lon": {
              "avg": {
                "script": "doc['loc'].lon"
              }
            }
          }
        }
      }
    }
  },
  "query": {
    "match_all": {}
  }
}

您可以 store your scripts on the file system 并在您的 query/aggregations 中引用它们。

使用以下内容创建名为 config/scripts/lat.groovy 的文件

 doc['loc'].lat

使用以下内容创建另一个名为 config/scripts/lon.groovy 的文件

 doc['loc'].lon

然后将您的查询更改为:

{
  "size": 0,
  "aggs": {
    "filtered_cells": {
      "filter": {
        "geo_bounding_box": {
          "loc": {
            "top_left": "58.645976, -13.515625",
            "bottom_right": "50.524473, 2.436523"
          }
        }
      },
      "aggs": {
        "cells": {
          "geohash_grid": {
            "field": "loc",
            "precision": 2
          },
          "aggs": {
            "center_lat": {
              "avg": {
                "script_file": "lat"
              }
            },
            "center_lon": {
              "avg": {
                "script_file": "lon"
              }
            }
          }
        }
      }
    }
  },
  "query": {
    "match_all": {}
  }
}

除了像我提到的那样将实际脚本放在 .groovy 文件中(更多细节 here), you could define a native script. More involved than the groovy-on-file approach but is much more flexible. In your case, the script is really simple :-) and you don't need the flexibility though, but the option exists (implementation sample from yours truly): ElasticSearch: aggregation on _score field w/ Groovy disabled