欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

es 单条数据更新

程序员文章站 2024-03-25 13:04:16
...

单条 object 数据更新:覆盖更新、部分更新 

# 删除索引
DELETE student-001
# 创建索引
PUT student-001
{
  "settings": {
    "number_of_shards": 3
  },
  "mappings": {
    "properties": {
      "id": {
        "type": "long"
      },
      "name": {
        "type": "text",
        "fields": {
          "key": {
            "type": "keyword"
          }
        }
      },
      "year": {
        "type": "integer",
        "fields": {
          "key": {
            "type": "keyword"
          }
        }
      }
    }
  }
}

批量添加数据


PUT _bulk
{"index":{"_index":"student-001","_id":1}}
{"id": 1,"name": "student-1","year": 1}
{"index":{"_index":"student-001","_id":2}}
{"id": 2,"name": "student-2","year": 2}
{"index":{"_index":"student-001","_id":3}}
{"id": 3,"name": "student-3","year": 3}
{"index":{"_index":"student-001","_id":4}}
{"id": 4,"name": "student-4","year": 1}
{"index":{"_index":"student-001","_id":5}}
{"id": 5,"name": "student-5","year": 3}

1 覆盖式更新

会把旧数据替换掉

PUT student-001/_doc/1?refresh=true
{
  "id": 1,
  "name": "student-1",
  "year": 1
}

2 部分更新

部分更新,有两种方式

把 id 为1的数据的 name 字段更新

POST student-001/_update/1?refresh=true
{
  "doc": {
    "name": "student-123"
  }
}

此时,如果数据不存在,会报错。如果我们想要这样的效果:如果数据不存在,则作为新数据添加;如果数据已经存在,则更新旧数据。那么我们可以添加参数 doc_as_upsert

POST student-001/_update/1?refresh=true
{
  "doc": {
    "name": "student-23"
  },
  "doc_as_upsert": true
}

可以使用脚本的方式来更新数据

POST student-001/_update/1?refresh=true
{
  "script": {
    "source": "ctx._source.name='student-1'"
  }
}

ctx._source.字段=值