Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch painless, how to determine the data type of a field

In es5.5, how to determine whether a field is numeric?

if (is_numeric(ctx._source.some)) {
    ctx._source.some = ctx._source.some + 2
}
like image 865
Allen_Tsang Avatar asked Nov 15 '25 07:11

Allen_Tsang


2 Answers

The instanceof operator might help here

if (ctx._source.some instanceof byte ||
    ctx._source.some instanceof short ||
    ctx._source.some instanceof int ||
    ctx._source.some instanceof long ||
    ctx._source.some instanceof float ||
    ctx._source.some instanceof double)
{
    ctx._source.some = ctx._source.some + 2
}
like image 93
Oleg Grishko Avatar answered Nov 17 '25 20:11

Oleg Grishko


Another approach is to use Debug.explain, see https://www.elastic.co/guide/en/elasticsearch/painless/6.8/painless-debugging.html

This will abort with a painless_explain_error and the output will tell you what classes are involved. With that information (obtained manually from your various indices across your various ElasticSearch versions), you can then implement Painless with instanceof, as shown in @oleg-grishko 's answer.

POST /hockey/player/1/_explain
{
  "query": {
    "script": {
       "script": "Debug.explain(doc.goals)"
    }
  }
}

{
   "error": {
      "type": "script_exception",
      "painless_class": "org.elasticsearch.index.fielddata.ScriptDocValues.Longs",
       ...
like image 45
mgaert Avatar answered Nov 17 '25 22:11

mgaert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!