1、什么是partial update

put /index/_doc/id 进行创建文档和替换文档,就是一样的语法,
在对应的应用程序中,每次执行的流程是这样的

  1. 应用程序发起get请求,获取document在页面中展示,供用户查看和修改
  2. 在页面中修改数据,发送到后台
  3. 将用户在页面中修改的数据在内存中执行,然后封装好全量数据
  4. 让后发送put请求到es中进行全量替换
  5. es将老的document 标记为deleted ,然后重新创建一个新的document

partial updata就是post

  1. POST /liang/_update/1
  2. {
  3. "doc": {
  4. "filed": "test2" #需要修改的filed,不需要全量的数据
  5. }
  6. }
  7. {
  8. "_index" : "liang",
  9. "_type" : "_doc",
  10. "_id" : "1",
  11. "_version" : 7,
  12. "result" : "updated",
  13. "_shards" : {
  14. "total" : 2,
  15. "successful" : 1,
  16. "failed" : 0
  17. },
  18. "_seq_no" : 6,
  19. "_primary_term" : 1
  20. }

2、partial update的实现原理和优点

partial updata 和全量替换相比较的优点
1、所有的查询,修改和写回操作,都发生在es的内部,避免了网络传输数据的开销,大大提升性能
2、减少了查询和修改中的时间间隔,可以有效减少并发冲突的情况
image.png

3、基于painless实现partial update操作

es存在内置脚本支持,可以基于groovy脚本实现各种各样复杂的操作的 ~~
基于groovy脚本如何执行partial update~~
基于painless实现partial update操作
(1)内置脚本

  1. (1)准备数据
  2. PUT /partial/_doc/1
  3. {
  4. "num": 0,
  5. "tags":[]
  6. }
  7. (2)内置脚本(将字段num+1)
  8. POST /partial/_update/1
  9. {
  10. "script": "ctx._source.num+=1"
  11. }
  12. GET /partial/_doc/1
  13. {
  14. "_index" : "partial",
  15. "_type" : "_doc",
  16. "_id" : "1",
  17. "_version" : 2,
  18. "_seq_no" : 1,
  19. "_primary_term" : 1,
  20. "found" : true,
  21. "_source" : {
  22. "num" : 1,
  23. "tags" : [ ]
  24. }
  25. }
  26. (3)外部脚本
  27. es_script创建ecommerce_add_tags
  28. POST _scripts/ecommerce_add_tags
  29. {
  30. "script":{
  31. "lang":"painless",
  32. "source":"ctx._source.num += params.new_num"
  33. }
  34. }
  35. GET _scripts/ecommerce_add_tags #查询脚本
  36. 使用id引用外部脚本更新document
  37. POST /partial/_update/1
  38. {
  39. "script": {
  40. "id":"ecommerce_add_tags",
  41. "params": {
  42. "new_num":3
  43. }
  44. }
  45. }
  46. (4)用脚本删除文档
  47. POST _scripts/delete_document
  48. {
  49. "script":{
  50. "lang": "painless",
  51. "source": "ctx.op = ctx._source.price == params.num ? 'delete' : 'none'"
  52. }
  53. }
  54. POST /partial/_update/1
  55. {
  56. "script": {
  57. "id":"delete_document",
  58. "params": {
  59. "new_num":3
  60. }
  61. }
  62. }
  63. (5)upsert
  64. 如果指定的document不存在,就执行upsert中的初始化操作;
  65. 如果指定的document存在,就执行doc或者script指定的partial update操作

4、partial update乐观锁并发控制

image.png