Search code examples
elasticsearchelasticsearch-painless

Elasticsearch - script_fields, how to check some value in a nested field?


I have the following ES field :

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

I want to check if this nested field contains the code 1815495. I tried that :

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

I got the error, but where is my mistake? I think I am not so far from the solution.

"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
    }
  }
]

Thanks any help or advice !


Solution

  • You can try this:

    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;
            """
          }
        }
      }
    }