Home > database >  Elasticsearch script query - get map parameter by key
Elasticsearch script query - get map parameter by key

Time:12-01

After finding the value in params with field1 value, I try to aggregate with the found field value.

GET /_search
{
  "size" : 0,
  "query" : {
    "ids" : {
      "types" : [ ],
      "values" : [ "docId1", "docId2" .... ]
    }
  },
  "aggs": {
    "countries": {
      "terms": {
        "script": {
          "params": {
            "field1": "country",
            "field2": "test",
            "field3": "test"
          },
          "inline": "def syn = params['field1']; doc[syn].value"
        }
      }
    }
  }
}

It fails with the message below.

      "failures": [
         {
            "reason": {
               "type": "script_exception",
               "reason": "failed to run inline script [def syn = params['field1']; doc[syn].value] using lang [groovy]",
               "caused_by": {
                  "type": "missing_property_exception",
                  "reason": "No such property: params for class: 8f7af04189385c7d3c546861d4817e4ae8ca75f5"
               }
            }
         }
      ]

If I enter it directly without importing the value from params, it will be aggregation normally.

GET /_search
{
  "size" : 0,
  "query" : {
    "ids" : {
      "types" : [ ],
      "values" : [ "docId1", "docId2" .... ]
    }
  },
  "aggs": {
    "countries": {
      "terms": {
        "script": {
          "params": {
            "field1": "country",
            "field2": "test",
            "field3": "test"
          },
          "inline": "doc['country'].value"
        }
      }
    }
  }
}

Like this:

{
   ...
   "aggregations": {
      "how_to_merge": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": "KR",
               "doc_count": 90
            },
            {
               "key": "JP",
               "doc_count": 83
            },
            {
               "key": "US",
               "doc_count": 50
            },
            {
               "key": "BE",
               "doc_count": 9
            }
         ]
      }
   }
}

I am using groovy and elasticsearch version 2.2

I can't use Python or JavaScript, which requires additional plug-ins to be installed.

Why can't I get the values in params?

CodePudding user response:

If I'm not mistaken, in 2.2 you didn't need to prefix the parameter with params. in the script source. Try like this:

  "aggs": {
    "countries": {
      "terms": {
        "script": {
          "params": {
            "field1": "country",
            "field2": "test",
            "field3": "test"
          },
          "inline": "def syn = field1; doc[syn].value"
        }
      }
    }
  }
  • Related