Spring data elasticsearch使用update_by_query

背景:

需要實現(xiàn)根據(jù)某個條件更新es里面的一批數(shù)據(jù),如果一條條查出來然后去更新的話就效率比較低。

實現(xiàn):

ES接口調(diào)用

官方文檔

POST http://localhost:9200/article/_update_by_query
{
    "script": {
        "source":"ctx._source['status']=0;"
    },
    "query": {
        "term": {
            "userId": 1
        }
    } 
}

Spring data

環(huán)境:jdk8
語言:kotlin
框架:spring boot 2.4.5
寫了個服務,可以用注入的方式調(diào)用方法。方法的入?yún)ㄟ^濾條件和要修改的值。

@Component
class EsSearchService(
    private val esClient: RestHighLevelClient
) {
    fun updateByQuery(status: Int, userId: String): BulkByScrollResponse {
        val termQuery = TermQueryBuilder("userId", userId)
        val script = Script(
            ScriptType.INLINE,
            "painless",
            "ctx._source['status'] = params['status'];",
            mapOf("status" to status)
        )
        val request  = UpdateByQueryRequest("article")
        request.setScript(script).setQuery(termQuery)
        request.maxRetries = 10
        request.isAbortOnVersionConflict = true
        return esClient.updateByQuery(request , RequestOptions.DEFAULT)
    }
}

后續(xù)

去GitHub上查看spring-data-elasticsearch的源碼,發(fā)現(xiàn)4.2.x的版本用updateByQuery更加方便了。
官方給出的例子:
https://github.com/spring-projects/spring-data-elasticsearch/blob/4.2.x/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java

void shouldDoUpdateByQueryForExistingDocument() {
        // given
        final String documentId = nextIdAsString();
        final String messageBeforeUpdate = "some test message";
        final String messageAfterUpdate = "test message";

        final SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message(messageBeforeUpdate)
                .version(System.currentTimeMillis()).build();

        final IndexQuery indexQuery = getIndexQuery(sampleEntity);

        operations.index(indexQuery, index);
        indexOperations.refresh();

        final NativeSearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();

        final UpdateQuery updateQuery = UpdateQuery.builder(query)
                .withScriptType(org.springframework.data.elasticsearch.core.ScriptType.INLINE)
                .withScript("ctx._source['message'] = params['newMessage']").withLang("painless")
                .withParams(Collections.singletonMap("newMessage", messageAfterUpdate)).withAbortOnVersionConflict(true)
                .build();

        // when
        operations.updateByQuery(updateQuery, index);

        // then
        SampleEntity indexedEntity = operations.get(documentId, SampleEntity.class, index);
        assertThat(indexedEntity.getMessage()).isEqualTo(messageAfterUpdate);
    }

可惜想用的話需要升級spring boot版本,項目依賴太多了,沒有升級成功,以下是對應的版本表。官方文檔

image.png

Ref: https://jishuin.proginn.com/p/763bfbd29466

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容