Elasticsearch學(xué)習(xí)筆記(九)partial update
一、什么是partial update?
PUT /index/type/id,創(chuàng)建文檔&替換文檔,就是一樣的語法一般對(duì)應(yīng)到應(yīng)用程序中,每次的執(zhí)行流程基本是這樣的:(1)應(yīng)用程序先發(fā)起一個(gè)get請(qǐng)求,獲取到document,展示到前臺(tái)界面,供用戶查看和修改(2)用戶在前臺(tái)界面修改數(shù)據(jù),發(fā)送到后臺(tái)(3)后臺(tái)代碼,會(huì)將用戶修改的數(shù)據(jù)在內(nèi)存中進(jìn)行執(zhí)行,然后封裝好修改后的全量數(shù)據(jù)(4)然后發(fā)送PUT請(qǐng)求,到es中,進(jìn)行全量替換(5)es將老的document標(biāo)記為deleted,然后重新創(chuàng)建一個(gè)新的documentpartial updatePOST /index/type/id/_update{"doc": {"要修改的少數(shù)幾個(gè)field即可,不需要全量的數(shù)據(jù)"}}PUT /test_index/test_type/10{"test_field1": "test1","test_field2": "test2"}POST /test_index/test_type/10/_update{"doc": {"test_field2": "updated test2"}}看起來,好像就比較方便了,每次就傳遞少數(shù)幾個(gè)發(fā)生修改的field即可,不需要將全量的document數(shù)據(jù)發(fā)送過去
二、partial update實(shí)現(xiàn)原理以及其優(yōu)點(diǎn)
partial
update直接將數(shù)據(jù)更新到document中就完成了修改,不用事先先發(fā)起一個(gè)GET請(qǐng)求數(shù)據(jù)進(jìn)行修改然后在將修改后的數(shù)據(jù)發(fā)回去。
es內(nèi)部:partial update的執(zhí)行和全量替換一致。
(1)內(nèi)部先get獲取document
(2)將更新的field更新到document的json中
(3)將老的document標(biāo)記為deleted
(4)創(chuàng)建新的document
優(yōu)點(diǎn):
(1)所有查詢,修改和寫回操作均發(fā)生在同一個(gè)shard內(nèi),避免了不必要的網(wǎng)絡(luò)數(shù)據(jù)傳輸帶來的開銷,大大提升了性能(減少了兩次請(qǐng)求,一次GET請(qǐng)求,一次回寫請(qǐng)求)
(2)減少修改和查詢中的時(shí)間間隔,有效減少并發(fā)沖突的情況
(3)內(nèi)置樂觀鎖并發(fā)控制
POST
/test_index/test_type/id/_update?retry_on_conflict=2
{"doc": {"num":32}}如果更新失敗,則獲取最新的版本號(hào)再次進(jìn)行更新,最多重試retry_on_conflict指定的次數(shù)
POST
/test_index/test_type/11/_update?version=3
{"doc": {"num":32}}
三、基于groovy腳本的partial update
1、內(nèi)置腳本
示例:
PUT
/test_index/test_type/11
{"num":0,"tags":[]}
更新num字段:
POST /test_index/test_type/11/_update{"script": "ctx._source.num+=8"}
2、外部腳本
在Elasticsearch的安裝目錄下的\config\scripts內(nèi)添加指定的groovy腳本
(1)添加腳本 test_update_num.groovy
腳本代碼:
ctx._source.num+=1
執(zhí)行腳本:
POST /test_index/test_type/11/_update{"script": {"lang": "groovy","file": "test_update_num"}}
( 2)添加腳本:test-add-tags.groovy
腳本代碼:ctx._source.tags+=new_tag
執(zhí)行腳本:
POST
/test_index/test_type/11/_update
{"script": {"lang": "groovy","file": "test-add-tags","params": {"new_tag":"tag_value"}}}
( 3)添加腳本:test-delete-document.groovy
腳本代碼:
ctx.op=ctx._source.num==count?"delete":'none'
執(zhí)行腳本:
POST /test_index/test_type/11/_update{"script": {"lang": "groovy","file": "test-delete-document","params": {"count":17}}}
(4)upsert操作
如果指定的document不存在,就執(zhí)行upsert中的初始化操作;如果指定的document存在,就執(zhí)行doc或者script指定的partial
update操作
POST /test_index/test_type/11/_update{"script" : "ctx._source.num+=1","upsert": {"num": 0,"tags": []}}
道在我心,一以貫之 HanWang

浙公網(wǎng)安備 33010602011771號(hào)