springboot2.1.8+elasticsearch7.3.2(六),删除DeleteRequest

我的DEMO项目下载:https://gitee.com/zhuhongliang/soringboot_elastic_search_732.git

看删除代码:

/**
 * 删除文档
 * @param indeces 索引
 * @param delete_id 要删除的id
 */
public void deleteById(String indeces, String delete_id){
    DeleteRequest request = new DeleteRequest(indeces.toLowerCase(), delete_id);
    // 等待主分片可用的超时时间
    request.timeout(TimeValue.timeValueMinutes(10));
    DeleteResponse deleteResponse = null;
    try {
        deleteResponse = client.delete(request, RequestOptions.DEFAULT);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String index = deleteResponse.getIndex();
    String id = deleteResponse.getId();
    long version = deleteResponse.getVersion();
    log.info("index:" + index + "; id:" + id + ",version:" + version);
    //判断删除的文档是否存在 :
    if(deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND){
        log.error("未找到需要删除的文档!");
        return;
    }
    ReplicationResponse.ShardInfo shardInfo = deleteResponse.getShardInfo();
    if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
        log.error("未完全执行所有分片,总分片数为:" + shardInfo.getTotal() + ",执行的分片数为:"+ shardInfo.getSuccessful());
    }
    if (shardInfo.getFailed() > 0) {
        for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
            String reason = failure.reason();
            log.error("失败原因:" + reason);
            return;
        }
    }
}
/**
 * 批量删除文档
 * @param list
 */
public void deleteMultiDoc(String index, List<String> list){
    BulkRequest request = new BulkRequest();
    /**
     * 遍历
     * IndexRequest不设置id,让系统自己添加
     * DeleteRequest 批量删除
     * UpdateRequest 批量更新
     */
    list.forEach((id)->{
        request.add(new DeleteRequest(index.toLowerCase(), id));
    });
    try {
        BulkResponse bulkResponse = client.bulk(request,RequestOptions.DEFAULT);
        bulkResponse.forEach((BulkItemResponse bulkItemResponse)->{
            DocWriteResponse itemResponse = bulkItemResponse.getResponse();
            switch (bulkItemResponse.getOpType()) {
                case INDEX:
                case CREATE:
                    IndexResponse indexResponse = (IndexResponse) itemResponse;
                    break;
                case UPDATE:
                    UpdateResponse updateResponse = (UpdateResponse) itemResponse;
                    break;
                case DELETE:
                    DeleteResponse deleteResponse = (DeleteResponse) itemResponse;
                    log.info(JSONObject.toJSONString(deleteResponse));
                    if(DocWriteResponse.Result.UPDATED == deleteResponse.getResult()){
                        log.info("删除成功");
                    }
                    break;
                default:break;
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

测试方法:

按id删除单个文档

@Test
public void deleteDoc(){
    //先搜索一批文档
    int page =1;
    int size =1;
    System.out.println("===================先随便查询查询一个数据=========================");
    SearchHit[] hits = commodityServiceImpl.searchDoc(Article.class, "黄昏",(page-1)*size ,size,"content");
    log.info("hits的数量:{}",hits.length);
    ArrayList<String> list = new ArrayList<>(4);
    if(hits.length==0){
        log.info("没有查询到数据,先添加数据吧");
        return;
    }
    System.out.println("===================删除数据=========================");
    commodityServiceImpl.deleteById(Article.class.getSimpleName(), hits[0].getId());
    //暂停五秒
    try {
        Thread.sleep(5*1000L);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("===================再次查询数据,确认删除是否成功=========================");
    SearchHit[] find_hits = commodityServiceImpl.findById(Article.class, hits[0].getId());
    log.info("find_hits的数量:{}",find_hits.length);
}

批量删除文档

@Test
public void deleteMultiDoc(){
    //先搜索一批文档
    int page =1;
    int size =10;
    System.out.println("===================查询数据=========================");
    SearchHit[] hits = commodityServiceImpl.searchDoc(Article.class, "物是人非",(page-1)*size ,size,"content");
    log.info("hits的数量:{}",hits.length);
    ArrayList<String> list = new ArrayList<>(16);
    if(hits.length>=1){
        for (SearchHit hit : hits) {
            list.add(hit.getId());
        }
    }else{
        log.info("没有查询到数据,先添加数据");
        return;
    }
    System.out.println("===================批量删除数据=========================");
    commodityServiceImpl.deleteMultiDoc(Article.class.getSimpleName(), list);
    //暂停五秒,等待数据删除之后再查询
    try {
        Thread.sleep(5*1000L);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("===================再次查询数据,确认批量删除是否成功=========================");
    SearchHit[] find_hits = commodityServiceImpl.searchDoc(Article.class, "物是人非",(page-1)*size ,size,"content");
    log.info("find_hits的数量:{}",find_hits.length);
}


运行单个删除

===================先随便查询查询一个数据=========================
2019-09-21 15:38:17.143  INFO 280916 --- [           main] c.z.e.service.impl.ServiceImpl           : fieldName.length:1,fieldName:[content]
2019-09-21 15:38:17.419  INFO 280916 --- [           main] c.z.e.ElasticsearchDemoApplicationTests  : hits的数量:1
===================删除数据=========================
2019-09-21 15:38:17.466  INFO 280916 --- [           main] c.z.e.service.impl.ServiceImpl           : index:article; id:LjODT20Bk6nS0BLhTTX_,version:2
===================再次查询数据,确认删除是否成功=========================
2019-09-21 15:38:22.470  INFO 280916 --- [           main] c.z.e.ElasticsearchDemoApplicationTests  : find_hits的数量:0


运行批量删除删除

===================查询数据=========================
2019-09-21 15:38:57.497  INFO 282732 --- [           main] c.z.e.service.impl.ServiceImpl           : fieldName.length:1,fieldName:[content]
2019-09-21 15:38:57.849  INFO 282732 --- [           main] c.z.e.ElasticsearchDemoApplicationTests  : hits的数量:3
===================批量删除数据=========================
2019-09-21 15:38:58.026  INFO 282732 --- [           main] c.z.e.service.impl.ServiceImpl           : {"fragment":false,"id":"-jW4Um0Bk6nS0BLh5kJH","index":"article","primaryTerm":1,"result":"DELETED","seqNo":15,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"article","uUID":"_na_"},"indexName":"article"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":1},"type":"_doc","version":3}
2019-09-21 15:38:58.026  INFO 282732 --- [           main] c.z.e.service.impl.ServiceImpl           : {"fragment":false,"id":"_TW4Um0Bk6nS0BLh5kKL","index":"article","primaryTerm":1,"result":"DELETED","seqNo":16,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"article","uUID":"_na_"},"indexName":"article"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":1},"type":"_doc","version":3}
2019-09-21 15:38:58.027  INFO 282732 --- [           main] c.z.e.service.impl.ServiceImpl           : {"fragment":false,"id":"LzODT20Bk6nS0BLhTTX_","index":"article","primaryTerm":1,"result":"DELETED","seqNo":17,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"article","uUID":"_na_"},"indexName":"article"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":1},"type":"_doc","version":5}
===================再次查询数据,确认批量删除是否成功=========================
2019-09-21 15:39:03.028  INFO 282732 --- [           main] c.z.e.service.impl.ServiceImpl           : fieldName.length:1,fieldName:[content]
2019-09-21 15:39:03.031  INFO 282732 --- [           main] c.z.e.ElasticsearchDemoApplicationTests  : find_hits的数量:0


都很简单

我的DEMO项目下载:https://gitee.com/zhuhongliang/soringboot_elastic_search_732.git

要发表评论,您必须先登录