首页 > 解决方案 > 如何在elasticsearch中更新和剥离数组字段的第一个字符

问题描述

我在弹性搜索的索引中有以下内容,列为 json doc

当前的

{
"bar": {
    "bar": [{
            "bar": [{
                    "bar": [{
                            "foo": "Y111111111111"
                        }
                    ]
        }
    ]
}

} }

需要更新

{
"bar": {
    "bar": [{
            "bar": [{
                    "bar": [{
                            "foo": "111111111111"
                        }
                    ]
        }
    ]
}

} }

我将如何更新索引以去除等于 bar 的字符串的第一个字符?

我尝试了以下适用于单个字段的语法,但在数组字段上运行时收到异常

{
  "error": {
  "root_cause": [
  {
    "type": "script_exception",
    "reason": "runtime error",
    "script_stack": [
      "ctx._source.foo = ctx._source.foo.substring(1);",
      "           ^---- HERE"
    ],
    "script": "ctx._source.foo = ctx._source.foo.substring(1);",
    "lang": "painless"
  }
 ],
 "type": "script_exception",
 "reason": "runtime error",
 "script_stack": [
  "ctx._source.foo = ctx._source.foo.substring(1);",
  "           ^---- HERE"
],
"script": "ctx._source.foo = ctx._source.foo.substring(1);",
"lang": "painless",
"caused_by": {
  "type": "illegal_argument_exception",
  "reason": "Illegal list shortcut value [foo]."
  }
 },
 "status": 400
}




POST test/_update_by_query 
{
"query": {
"prefix": {
  "foo": "Y"
}
},
"script": {
"source": "ctx._source.foo = ctx._source.foo.substring(1);"
}

映射

{
"TEST": {
    "mappings": {
        "properties": {
            "bar": {
                "properties": {
                "bar": {
                        "properties": {
                            "bar: {
                                "properties": {
                                "bar": {
                                        "properties": {
                                        "foo": {
                                                "type": "keyword"
                                            }
                                            }
                                    }
                                }
                            }
                        }
                    }
                   }
            }
        }
    }
    }

}

标签: elasticsearchelasticsearch-scripting

解决方案


我会这样做如下。查找foo字段以开头的所有文档,Y然后foo通过剥离第一个字符来更新所有字段:

POST test/_update_by_query
{
  "query": {
    "prefix": {
      "bar.bar.bar.bar.foo": "Y"
    }
  },
  "script": {
    "source": "ctx._source.bar.bar[0].bar[0].bar[0].foo = ctx._source.bar.bar[0].bar[0].bar[0].foo.substring(1);"
  }
}

PS:查询将取决于您的bar字段是否嵌套,但如果不是,上述查询应该可以工作。


推荐阅读