es elasticsearch 新增字段 field 并设置值

参考链接: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"
          }
        }
      ]
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值