Elasticsearch - script_fields,如何检查嵌套字段中的某个值?

guykilcj  于 2023-05-06  发布在  ElasticSearch
关注(0)|答案(1)|浏览(143)

我有以下ES字段:

"myNestedField" : [
      {
        "ref" : "34781000 + 27598001",
        "image" : "img1",
        "code" : "3219370",
        "label" : "my pack"
      },
      {
        "ref" : "27598001",
        "image" : "img2",
        "code" : "1815495",
        "label" : "my bag"
      }
    ]

我想检查这个嵌套字段是否包含代码1815495。我试过了

"script_fields": {
        "boolFieldToReturn": {
        "script": {
          "source": " for (item in params._source.myNestedField) {if (item.code== '1815495') return true; else return false; }"
          }
        }
      }

我犯了错误,但我的错误在哪里?我想我离解决方案不远了。

"root_cause" : [
  {
    "type" : "script_exception",
    "reason" : "compile error",
    "script_stack" : [
      " for (item in params._sour ...",
      " ^---- HERE"
    ],
    "script" : " for (item in params._source.myNestedField){if (item.code== '2815495') return true; else return false; }",
    "lang" : "painless",
    "position" : {
      "offset" : 1,
      "start" : 0,
      "end" : 26
    }
  }
]

感谢任何帮助或建议!

uqzxnwby

uqzxnwby1#

你可以试试这个:

GET test/_search
{
  "script_fields": {
    "boolFieldToReturn": {
      "script": {
        "source": """
          def found = false;
          for (item in params._source.myNestedField) {
            if(item.code== '1815495'){
              found = true;
              break
            }
          }
          return found;
        """
      }
    }
  }
}

相关问题