如何在Elasticsearch中更新和剥离数组字段的第一个字符

问题描述

我在弹性搜索的索引中包含以下内容,列为json文档

当前

{
"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","script_stack": [
  "ctx._source.foo = ctx._source.foo.substring(1);","           ^---- HERE"
],"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"
                                            }
                                            }
                                    }
                                }
                            }
                        }
                    }
                   }
            }
        }
    }
    }

}

解决方法

我将按照以下步骤进行操作。查找所有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字段是否嵌套,但如果不嵌套,则上述查询应该起作用。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...