数学函数不适用于ElasticSearch脚本中的运算符

ES版本:number: "7.0.1",

以下查询不起作用。它返回illegal_argument_exception(下面是完整堆栈)。

   {
      "query": {
        "function_score": {
          "query": {
            "query_string": {
              "query": "SOME_QUERY"
            }
          },"script_score": {
            "script": {
              "source": "Math.log(doc['SOME_FIELD'].value + 1)"
            }
          }
        }
      }
    }

尽管我可能会遇到doc['SOME_FIELD'].value的问题,但显然在使用运算符(在这种情况下为Math.*)的+函数中存在语法问题:

  • "source": "Math.log(doc['SOME_FIELD'].value + 1)"不起作用
  • "source": "Math.log(1 + 1)"不起作用

同时

  • "source": "doc['SOME_FIELD'].value"作品
  • "source": "1 + 1"作品
  • "source": "Math.log(1)"作品

全栈跟踪:

{
      "error": {
        "root_cause": [
          {
            "type": "script_exception","reason": "compile error","script_stack": [
              "NaN","^---- HERE"
            ],"script": "NaN","lang": "painless"
          }
        ],"type": "search_phase_execution_exception","reason": "all shards failed","phase": "query","grouped": true,"failed_shards": [
          {
            "shard": 0,"index": "index","node": "69HAL8sMS-afWoTxhMteKw","reason": {
              "type": "query_shard_exception","reason": "script_score: the script could not be loaded","index_uuid": "ASy6y5zxRpqMFONSLED6IQ","caused_by": {
                "type": "script_exception","script_stack": [
                  "NaN","^---- HERE"
                ],"lang": "painless","caused_by": {
                  "type": "illegal_argument_exception","reason": "Variable [NaN] is not defined."
                }
              }
            }
          }
        ],"caused_by": {
          "type": "script_exception","script_stack": [
            "NaN","^---- HERE"
          ],"caused_by": {
            "type": "illegal_argument_exception","reason": "Variable [NaN] is not defined."
          }
        }
      },"status": 400
    }
wxt112 回答:数学函数不适用于ElasticSearch脚本中的运算符

doc ['SOME_FIELD']。value中的值可能不是数字(NaN)。根据期望的数字类型,您可以(并且应该)使用正则表达式评估脚本中的值,以确定其是否正确解析,如下所示:

def m = /^([0-9]+)$/.matcher(doc['SOME_FIELD'].value);
if (m.matches()) { 
  def number = Integer.parseInt(doc['SOME_FIELD'].value);
    if (number == SOMENUMBER) return true;
    else return false;
} else return false;

请记住,如果您正在运行此脚本,则需要将脚本全部放在一行上。

此外,您还需要在集群上启用正则表达式(如果它不在弹性搜索yaml文件中)。

本文链接:https://www.f2er.com/3151731.html

大家都在问