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