elasticsearch 5.x Delete By Query API(根據條件刪除)

以前在 2.X版本里 這個Delete By Query功能被去掉了 由於官方認爲會引起一些錯誤 如需使用 須要本身安裝插件。html

bin/plugin install delete-by-query

須要使用時java

DELETE /索引名/須要清空的type/_query { "query": { "match_all": {} } }

那麼在5.x版本中 這個api又被官方從新加回自帶功能。新特性裏是這麼說的。api

Delete-by-query 和 Update-by-query 從新回到 core ,之前是插件,如今能夠直接使用了, 也是構建在 Reindex 機制之上。 (es1.x版本是直接支持,在es2.x中提取爲插件,5.x繼續迴歸直接支持)

我查看了官方手冊後發現使用也不同了 見下圖elasticsearch

官方地址:https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-delete-by-query.htmlide

即替換之前的 _query 爲_delete_by_query 即可達到目的。post

經過header插件刪除ui

使用head插件刪除指定數據 http://serverhost:9200/index/type/_delete_by_query post
 { "query": { "match": { 屬性字段: 要刪除的屬性值 } } }

Java代碼實現:spa

String index = "wareic"; BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); queryBuilder.must(QueryBuilders.termQuery("groupID", "42023")); BulkIndexByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(client) .filter(queryBuilder) .source(index) .get(); long deleted = response.getDeleted(); System.out.println(deleted);

另外一種實現方式:插件

String index = "wareic"; String type = "product"; BulkRequestBuilder bulkRequest = client.prepareBulk(); SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index).setTypes(type); //分頁
searchRequestBuilder.setFrom(0).setSize(1000); BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); queryBuilder.must(QueryBuilders.termQuery("groupID", "3445")); searchRequestBuilder.setQuery(queryBuilder); SearchResponse response = searchRequestBuilder.execute().get(); for(SearchHit hit : response.getHits()){ String id = hit.getId(); bulkRequest.add(client.prepareDelete(index, type, id).request()); } BulkResponse bulkResponse = bulkRequest.get(); if (bulkResponse.hasFailures()) { for(BulkItemResponse item : bulkResponse.getItems()){ System.out.println(item.getFailureMessage()); } } else { System.out.println("delete ok"); } 

文章參考地址:https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.2/java-docs-delete-by-query.htmlcode

相關文章
相關標籤/搜索