参考链接:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html#:~:text=When%20you%20submit%20an%20update%20by%20query%20request%2C,is%20updated%20and%20the%20version%20number%20is%20incremented.

1. 在 mapping 中新增映射字段:

PUT test/_mapping
{
  "properties": {
    "addTestField": {
      "type": "boolean"
    }
  }
}

2. update by query 根据条件查询数据,给查询出的数据新增字段并设置值。

  1. 在这里因为是新增字段,所以查询条件是 match_all 即,给所有的文档都新增字段。
  2. conflicts=proceed 表示的意思是遇到版本冲突的是继续往下处理,忽略冲突。
POST test/_update_by_query?conflicts=proceed
{
  "script": {
    "source": "ctx._source.addTestField=true",
    "lang": "painless"
  },
  "query": {
    "match_all": {}
  }
}
  1. script 中的 lang 是 painless 脚本语言,source 是用 painless 脚本语言写得代码。意思是给 addTestField 字段赋值 true 。

painless 脚本语言见 : https://www.elastic.co/guide/en/elasticsearch/painless/master/index.html

3. 查询还有哪些文档没有 addTestField 字段。

因为新增字段的时候,可能业务系统也在更新同一条数据,所以会更新失败。所以,有些数据的 addTestField 字段会没有添加成功。

GET test/_search
{
  "query": {
    "bool": {
      "must_not": [
        {
          "exists": {
            "field": "addTestField"
          }
        }
      ]
    }
  }
}
4. 增量更新数据

因为部分文档会因为版本冲突,导致更新失败,所以接下来还需要增量更新。

POST test/_update_by_query?conflicts=proceed
{
  "script": {
    "source": "ctx._source.addTestField=true",
    "lang": "painless"
  },
  "query": {
    "bool": {
      "must_not": [
        {
          "exists": {
            "field": "addTestField"
          }
        }
      ]
    }
  }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐