Elasticsearch 整合 Spring Boot(4)

前邊我們已經(jīng)學(xué)習(xí)了 Spring Boot 整合 Elasticsearch 的索引創(chuàng)建、文檔查詢,最后我們來學(xué)習(xí)文檔更新以及刪除的相關(guān)用法。

1、文檔更新

根據(jù)文檔 id 更新:

public void updateBookById(String id) {
    Document document = Document.create();
    document.put("commentCount", 1214666);
    document.put("price", 66.6);
    UpdateQuery updateQuery = UpdateQuery.builder(id).withDocument(document).build();
    UpdateResponse response = elasticsearchRestTemplate.update(updateQuery, IndexCoordinates.of("book"));
    System.out.println(response.getResult().name());
}

主要就是使用Document設(shè)置要更新的字段,再通過UpdateQuery綁定文檔 id以及 Document。

如果需要根據(jù)多個文檔 id 批量更新,可以使用bulkUpdate()方法:

public void bulkUpdateBook(String... ids) {
    List<UpdateQuery> updateQueryList = new ArrayList<>();
    for (String id : ids) {
        Document document = Document.create();
        document.put("commentCount", 1214666);
        document.put("price", 66.6);
        UpdateQuery updateQuery = UpdateQuery.builder(id).withDocument(document).build();
        updateQueryList.add(updateQuery);
    }
    elasticsearchRestTemplate.bulkUpdate(updateQueryList, IndexCoordinates.of("book"));
}

2、刪除文檔

根據(jù)文檔 id 刪除:

public void deleteBookById(String id) {
    String result = elasticsearchRestTemplate.delete(id, Book.class);
    System.out.println(result);
}

自定義刪除條件,例如根據(jù) skuId 刪除:

public void deleteBookBySkuId(String skuId) {
    NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
            .withQuery(QueryBuilders.termQuery("skuId", skuId))
            .build();
    elasticsearchRestTemplate.delete(nativeSearchQuery, Book.class, IndexCoordinates.of("book"));
}

和查詢一樣,還是使用NativeSearchQueryBuilder構(gòu)建刪除的條件。

更多的詳細(xì)的內(nèi)容可以參考官方文檔。

本文詳細(xì)的代碼可以參考:https://github.com/SheHuan/LearnElasticsearch

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

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