How to use deletebyQuery elastic 8.x version ?
public long deleteESDocuments(String indexName, Map<String, Object> termQueryMap, Map<String, Object[]> rangeQueryMap) throws IOException{
log.debug("Inside deleteESDocuments method");
DeleteByQueryRequest request = null;
BulkByScrollResponse bulkResponse = null;
BoolQueryBuilder builder = null;
request = new DeleteByQueryRequest(indexName);
builder = QueryBuilders.boolQuery();
for(String key : termQueryMap.keySet()) {
builder.must(QueryBuilders.termQuery(key, termQueryMap.get(key)));
}
for (String key: rangeQueryMap.keySet()){
Object[] range = rangeQueryMap.get(key);
log.debug("{} range from {} to {}, ", key,range[0],range[1]);
builder.must(QueryBuilders.rangeQuery(key).gte(range[0]).lte(range[1]));
}
log.debug("builderQuery is: {} ", builder);
request.setQuery(builder);
bulkResponse = client.deleteByQuery(request, RequestOptions.DEFAULT);
log.debug("ES Document Deletion response: {}",bulkResponse.getStatus());
log.debug("{} ES Document/s is/are deleted.",bulkResponse.getDeleted());
return bulkResponse.getDeleted();
}
Hi @Manoj_Upadhyay ,
Are you receiving a particular error from the above code? Or is it not working in the way that you expect?
Hi Carly,
After ES 8. x upgrade, am using ElasticsearchClient in place of RestHighClient and don't see an option to use deleteByQuery. Tried to read the document but saw only option the to search first and then all IDs in DeleteByQueryRequest then delete them.
dadoonet
(David Pilato)
February 13, 2024, 3:24pm
4
Have a look at this example:
@Test
void deleteByQuery() throws IOException {
String INDEX = "dbq";
try {
client.indices().delete(dir -> dir.index(INDEX));
} catch (ElasticsearchException ignored) { }
client.index(ir -> ir.index(INDEX).id("1").withJson(new StringReader("{\"foo\":\"bar\"}")));
client.indices().refresh(rr -> rr.index(INDEX));
SearchResponse<Void> response = client.search(sr -> sr.index(INDEX), Void.class);
assertEquals(1L, response.hits().total().value());
DeleteByQueryResponse deleteByQueryResponse = client.deleteByQuery(dbq -> dbq
.index(INDEX)
.query(q -> q
.match(mq -> mq
.field("foo")
.query("bar"))));
assertEquals(1L, deleteByQueryResponse.deleted());
client.indices().refresh(rr -> rr.index(INDEX));
response = client.search(sr -> sr.index(INDEX), Void.class);
assertEquals(0L, response.hits().total().value());
}
Thanks a lot. if there is any direct APIs(similar to ES 7) to delete documents in bulk in place of finding the search result, iterating hits, and adding them in DeleteByQueryRequest then deleting them in bulk.
Thanks a lot for help and i got it
system
(system)
Closed
April 1, 2024, 11:07pm
7
This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.