Update
ES本身还是一个倾向于查询检索的框架,对于这种更新的操作,太过频繁是不好的。
将旧文档标记为删除状态,然后添加新的文档,旧的文档不会立刻消失,但是也不可访问
本篇文章包含使用Script对所有的文档执行更新操作,也可以使用doc对部分文档执行更新,也可以使用upsert对不存在的文档执行添加操作。
全部更新 PUT
curl -XPUT localhost:9200/test/type1/1 -d '{"counter" : 1,"tags" : ["red"]}'
部分更新 POST
POST index/_doc/id/_update{"doc" : {"callBackStatus" : 1,"callBackCno":"1045","callBackCname":"zhaojy"}}
脚本更新
可以通过ctx来获得_source、``_index、_type、_id、_version、_parent、_timestamp、_ttl等字段信息。
脚本教程
https://blog.csdn.net/u013613428/article/details/78134170
1. 计数增加
curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{"script" : {"inline": "ctx._source.counter += params.count","params" : {"count" : 4}}}'
2. 增加标签
curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{"script" : {"inline": "ctx._source.tags += params.tag","params" : {"tag" : "blue"}}}'
3. 存在则更新
POST test/_doc//_update{"script" : {"source": "if (ctx._source.tags.contains(params.tag)) { ctx.op = 'delete' } else { ctx.op = 'none' }","lang": "painless","params" : {"tag" : "green"}}}
字段更新
添加某个字段:
curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{"script" : "ctx._source.name_of_new_field = \"value_of_new_field\""}'
移除字段:
curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{"script" : "ctx._source.remove(\"name_of_field\")"}'
upsert
存在就更新,不存在插入
curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{"script" : {"inline": "ctx._source.counter += count","params" : {"count" : 4}},"upsert" : {"counter" : 1}}'
在上面的例子中,当文档存在时,执行脚本;当文档不存在时,upsert中的内容就会插入到对应的文档中。
如果你想无论文档是否存在都执行脚本操作,那么可以使用参数scripted_upsert为true。
注意:ctx._source.counter字段不能是空,否则报空指针异常
curl -XPOST 'localhost:9200/sessions/session/dh3sgudg8gsrgl/_update' -d '{"scripted_upsert":true,"script" : {"id": "my_web_session_summariser","params" : {"pageViewEvent" : {"url":"foo.com/bar","response":404,"time":"2014-01-01 12:32"}}},"upsert" : {}}'
update_by_query
POST /user_bigtable/_doc/_update_by_query{"script": {"source": "ctx._source['saleaccount']='lixiaona10029'"},"query": {"bool": {"must_not": [{"exists": {"field": "area"}}],"must": [{"term":{"classid":217007}},{"term":{"periodid":90001}}]}}}
查询更新
https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html
Delete
将旧文档标记为删除状态,然后添加新的文档,旧的文档不会立刻消失,但是也不可访问
curl -XDELETE master:9200/bigdata/product/4—->根据指定的索引id进行删除
POST index_*/_delete_by_query{"query": {"match": {"userId": XXX}}}
更多文章:
- https://www.cnblogs.com/xing901022/p/5330778.html
- https://my.oschina.net/u/1027043/blog/1648749?from=mail-notify
- https://blog.csdn.net/weixin_39800144/article/details/80524373
- 常用 api: https://www.bbsmax.com/A/E35pnaWbzv/
参考文章:
