Elasticsearch, can't remove a field inside nested field

Viewed 951

I have mappings

{
  "candidate-index" : {
    "mappings" : {
      "properties" : {
        "provider_candidates" : {
          "type" : "nested",
          "properties" : {
            "foo" : {
              "type" : "object"
            },
            "group_key" : {
              "type" : "keyword"
            }
          }
        }
      }
    }
}

I want to delete foo field

 POST /candidate-index/_update_by_query
 {
   "script" : "ctx._source.remove(\"provider_candidates.foo\")",
   "query": {
     "nested": {
       "path": "provider_candidates",
       "query": {
         "bool": {
           "must": [
             {
               "exists": {
                 "field": "provider_candidates.foo"
               }
             }
           ]


         }
       }
     }
   }
 }

It doesn't work. It doesn't generate an error, but the field is not removed.
I know the query part is correct, because if I turn it into _search it correctly finds documents

I also tried

 POST /candidate-index/_update_by_query
 {
   "script" : "ctx._source.provider_candidates.remove(\"foo\")",
   "query": {
     "nested": {
       "path": "provider_candidates",
       "query": {
         "bool": {
           "must": [
             {
               "exists": {
                 "field": "provider_candidates.foo"
               }
             }
           ]


         }
       }
     }
   }
 }

it says

{
  "error" : {
    "root_cause" : [
      {
        "type" : "script_exception",
        "reason" : "runtime error",
        "script_stack" : [
          "ctx._source.provider_candidates.remove(\"foo\")",
          "                               ^---- HERE"
        ],
        "script" : "ctx._source.provider_candidates.remove(\"foo\")",
        "lang" : "painless"
      }
    ],
    "type" : "script_exception",
    "reason" : "runtime error",
    "script_stack" : [
      "ctx._source.provider_candidates.remove(\"foo\")",
      "                               ^---- HERE"
    ],
    "script" : "ctx._source.provider_candidates.remove(\"foo\")",
    "lang" : "painless",
    "caused_by" : {
      "type" : "wrong_method_type_exception",
      "reason" : "cannot convert MethodHandle(List,int)Object to (Object,String)Object"
    }
  },
  "status" : 400
}
1 Answers

You need to loop provider_candidates field and then delete field inside it

POST /index51/_update_by_query
 {
  "script" : "for (int i = 0; i < ctx._source.provider_candidates.length; ++i) { ctx._source.provider_candidates[i].remove(\"foo\") }",
   "query": {
     "nested": {
       "path": "provider_candidates",
       "query": {
         "bool": {
           "must": [
             {
               "exists": {
                 "field": "provider_candidates.foo"
               }
             }
           ]
         }
       }
     }
   }
 }

Related