ES中更新字段和删除字段的操作

简介: ES中更新字段和删除字段的操作

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站点击跳转浏览。


ES中更新某一个字段,以及添加某一个字段


PUT test/type1/1
{
    "counter" : 1,
    "tags" : ["red"]
}

执行以下操作


POST test/type1/1/_update
{
    "script" : {
        "source": "ctx._source.counter += params.count",
        "lang": "painless",
        "params" : {
            "count" : 4
        }
    }
}

查看一下结果

{
  "_index": "test",
  "_type": "type1",
  "_id": "1",
  "_version": 3,
  "found": true,
  "_source": {
    "counter": 5,
    "tags": [
      "red"
    ]
  }
}

执行二

POST test/type1/1/_update
{
    "script" : {
        "source": "ctx._source.tags.add(params.tag)",
        "lang": "painless",
        "params" : {
            "tag" : "blue"
        }
    }
}

查看结果

{
  "_index": "test",
  "_type": "type1",
  "_id": "1",
  "_version": 2,
  "found": true,
  "_source": {
    "counter": 1,
    "tags": [
      "red",
      "blue"
    ]
  }
}

除_source外,通过ctx映射还可以使用以下变量:_index,_type,_id,_version,_routing,_parent和_now(当前时间戳)。

还可以在文档中添加一个新字段


POST test/type1/1/_update
{
    "script" : "ctx._source.new_field = 'value_of_new_field'"
}


结果如下:


{
  "_index": "test",
  "_type": "type1",
  "_id": "1",
  "_version": 4,
  "found": true,
  "_source": {
    "counter": 5,
    "tags": [
      "red",
      "blue"
    ],
    "new_field": "value_of_new_field"
  }
}


ES中删除某个字段


POST test/type1/1/_update
{
    "script" : "ctx._source.remove('new_field')"
}

查看一下数据


{
  "_index": "test",
  "_type": "type1",
  "_id": "1",
  "_version": 5,
  "found": true,
  "_source": {
    "counter": 5,
    "tags": [
      "red",
      "blue"
    ]
  }
}


而且,我们甚至可以改变执行的操作: 如果标签字段包含蓝色,则此示例将删除该文档,否则它将不执行任何操作(noop)


POST test/type1/1/_update
{
    "script" : {
        "source": "if (ctx._source.tags.contains(params.tag)) { ctx.op = 'delete' } else { ctx.op = 'none' }",
        "lang": "painless",
        "params" : {
            "tag" : "blue"
        }
    }
}


查看一下数据


{
  "_index": "test",
  "_type": "type1",
  "_id": "1",
  "found": false
}
相关文章
|
SQL 关系型数据库 MySQL
使用tkmapper避免更新on update字段
使用tkmapper避免更新on update字段
151 0
ES删除索引和测试关于文档的操作
ES删除索引和测试关于文档的操作
EF部分字段更新,自动忽略null字段
原文:EF部分字段更新,自动忽略null字段  某个项目里的update代码是类似这样的 public T Update(T entity) where T : ModelBase { var set = this.
1602 0
|
PHP
Laravel返回不重复的某个字段信息列表
->groupBy('brand_id') ->pluck('brand_id');  学习交流群:364976091
1983 0