4

Learning some elasticsearch here and I'm a bit stumped on using min and max functions in scripted field definitions. First,

GET my_index/_search
{
    "query" : {
        "match_all": {}
    },
    "script_fields" : {
        "test1" : {
            "script" : {
                "lang": "painless",
                "source": "min(doc[\"this field\"],5)"
            }
        }
    }
}

And I am rewarded with

"error": {
"root_cause": [
  {
    "type": "script_exception",
    "reason": "compile error",
    "script_stack": [
      "min(doc[\"end\"],5)",
      "^---- HERE"
    ],
    "script": "min(doc[\"end\"],5)",
    "lang": "painless"
  }
], ...

I thought maybe I needed to namespace it with Long.min and got back

"reason": "runtime error",
      "script_stack": [
        """Long.min(doc["end"],5)""",
        "            ^---- HERE"
      ],

This appears to be progress, but why would the problem be doc?

They appear to be in the painless API reference and I think it would be a little idiotic if they were not available. I keep searching for combinations of "painless min max function" but all I get is what I've linked above and a soup of unrelated things.

What am I doing wrong here?

rschwieb
  • 746
  • 2
  • 16
  • 41

1 Answers1

5

I finally stumbled across the answer. I had been using escaped quotes based on an example that I found, and replacing them with single quotes led me to error messages that got me to my working version. Another mistake I was making was not using the .value on doc['this field'] to recover the actual numerical type. The working version is:

GET my_index/_search
{
    "query" : {
        "match_all": {}
    },
    "script_fields" : {
        "test1" : {
            "script" : {
                "lang": "painless",
                "source": "Math.min(doc['this field'].value,5)"
            }
        }
    }
}

Double.min (matching the type of 'this field') worked too, but I gather that Math.min is meant to be more flexible.

rschwieb
  • 746
  • 2
  • 16
  • 41