前邊我們已經(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