Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query without using dynamic scripting

I have the following query which currently uses dynamic scripting. I have since found that my host doesn't support this, as it has wider reaching security implications. How would I rewrite this script so that it doesn't use dynamic script?

{
  "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": {}
  }
}
like image 695
Mick Walker Avatar asked Oct 20 '22 12:10

Mick Walker


2 Answers

You can store your scripts on the file system and reference them from within your query/aggregations.

Create a file named config/scripts/lat.groovy with the following content

 doc['loc'].lat

Create another file named config/scripts/lon.groovy with the following content

 doc['loc'].lon

Then change your query to this:

{
  "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": {}
  }
}
like image 185
Val Avatar answered Oct 22 '22 08:10

Val


Apart from placing the actual script on a .groovy file, like I mentioned (more details 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

like image 35
Andrei Stefan Avatar answered Oct 22 '22 09:10

Andrei Stefan