1、什么是partial update
全量替换PUT /index/type/id
创建文档&替换文档,就是一样的语法
全量替换一般对应到应用程序中,每次的执行流程基本是这样的:
(1)应用程序先发起一个get请求,获取到document,展示到前台界面,供用户查看和修改
(2)用户在前台界面修改数据,发送到后台
(3)后台代码,会将用户修改的数据在内存中进行执行,然后封装好修改后的全量数据
(4)然后发送PUT请求,到es中,进行全量替换
(5)es将老的document标记为deleted,然后重新创建一个新的document
partial update 更新
post /index/type/id/_update
{
"doc": {
"要修改的少数几个field即可,不需要全量的数据"
}
}
每次就传递少数几个发生修改的field即可,不需要将全量的document数据发送过去
2、partial update实现原理以及其优点
partial update不需要应用程序查询document数据,可以直接修改field并传递到es进行更新。
- 在es内部对partial update的实际执行,跟传统的全量替换方式几乎一样:
(1)内部先获取对应的document数据
(2)将传过来的field更新到document的json中
(3)将老的document标记为deleted
(4)将修改后的新的document创建出来 - partial update相较于全量替换的优点
(1)所有的查询、修改和写回操作都发生在es中的一个shard内部,避免了所有的网络传输的开销(减少2次网络请求),大大提高了性能
(2)减少了查询和修改中的时间间隔,可以有效地减少并发冲突的情况图解partial update实现原理以及其优点
3、动手实战演练partial update
------------------------首先添加一条document数据-----------------------
PUT /test_index/test_type/9
{
"test_field1":"test1",
"test_field2":"test2"
}
-------------------------------查询添加的结果----------------------------
GET /test_index/test_type/9
{
"_index": "test_index",
"_type": "test_type",
"_id": "9",
"_version": 1,
"found": true,
"_source": {
"test_field1": "test1",
"test_field2": "test2"
}
}
-------------------------------使用partial update更新数据----------------------------
POST /test_index/test_type/9/_update
{
"doc": {
"test_field2":"test update test"
}
}
-----------------------------------更新结果---------------------------------------
{
"_index": "test_index",
"_type": "test_type",
"_id": "9",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
-----------------------------------查询更新后结果---------------------------------------
GET /test_index/test_type/9
返回:
{
"_index": "test_index",
"_type": "test_type",
"_id": "9",
"_version": 2,
"found": true,
"_source": {
"test_field1": "test1",
"test_field2": "test update test"
}
}