首页 > 解决方案 > Elasticsearch,无法删除嵌套字段中的字段

问题描述

我有映射

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

我要删除foo字段

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


         }
       }
     }
   }
 }

它不起作用。它不会产生错误,但不会删除该字段。
我知道查询部分是正确的,因为如果我把它变成_search正确的找到文档

我也试过

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


         }
       }
     }
   }
 }

它说

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

标签: elasticsearch

解决方案


您需要循环 provider_candidates 字段,然后删除其中的字段

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


推荐阅读