4

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

if (is_numeric(ctx._source.some)) {
    ctx._source.some = ctx._source.some + 2
}
Allen_Tsang
  • 555
  • 1
  • 6
  • 14
  • Why don't you get the mapping and determine that? https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-field-mapping.html – sramalingam24 Mar 01 '18 at 03:33
  • i believe it can be done with painless. just don't get the way. – Allen_Tsang Mar 01 '18 at 10:19
  • There is an instanceof that can be used to check against a reference type which you probably can use to define you own is_numeric function – sramalingam24 Mar 02 '18 at 00:12
  • 1
    "why don't you get the mapping" - maybe because the mapping varies across indices, and you want to find the type per document ... maybe to unearth some type conflicts? Well - that's what *I'd* like to do at the moment. – jmb Mar 07 '19 at 17:23
  • @sramalingam24 mapping is not necessary giving you the exact field type. By instance, a field can be an array or a concrete value, you cannot control that with mapping. – Thomas Decaux Nov 29 '22 at 14:37

2 Answers2

4

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
}
Oleg Grishko
  • 4,132
  • 2
  • 38
  • 52
2

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",
       ...
mgaert
  • 2,338
  • 21
  • 27