springboot2.1.8+elasticsearch7.3.2(五),更新UpdateRequest

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

更新使用的是UpdateRequest()类,批量更新用的是BulkRequest()

看代码:

/**
 * 更新文档
 * @param obj
 * @param id
 */
public Boolean updateDoc(Object obj, String id){
    /**
     * 设置索引,必须是小写,所以使用toLowerCase()方法进行转换
     */
    UpdateRequest request = new UpdateRequest(obj.getClass().getSimpleName().toLowerCase(), id);
    request.doc(JSONObject.toJSONString(obj), XContentType.JSON);
    try {
        UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        updateResponse.getGetResult();
        if(DocWriteResponse.Result.UPDATED == updateResponse.getResult()){
            return true;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}


/**
 * 批量更新文档
 * @param list
 */
public void updateMultiDoc(List<HashMap<String,Object>> list){
    BulkRequest request = new BulkRequest();
    /**
     * 遍历
     * IndexRequest不设置id,让系统自己添加
     * DeleteRequest 批量删除
     * UpdateRequest 批量更新
     */
    list.forEach((map)->{
        Object obj = map.get("obj");
        request.add(
                new UpdateRequest(obj.getClass().getSimpleName().toLowerCase(), (String) map.get("id"))
                        .doc(JSONObject.toJSONString(obj), XContentType.JSON)
        );
    });
    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;
                    log.info(JSONObject.toJSONString(updateResponse));
                    if(DocWriteResponse.Result.UPDATED == updateResponse.getResult()){
                        log.info("更新成功");
                    }
                    break;
                case DELETE:
                    DeleteResponse deleteResponse = (DeleteResponse) itemResponse;
                    break;
                default:break;
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

测试方法:

/**
 * 更新
 */
@Test
public void updateDoc(){
    //先搜索一个文档
    int page =1;
    int size =1;
    System.out.println("===================只查询一条数据=========================");
    SearchHit[] hits = commodityServiceImpl.searchDoc(Article.class, "物是人非",(page-1)*size ,size, "content");
    String id;
    Article article;
    if(hits.length>=1){
        id = hits[0].getId();
        log.info("id:{}",id);
        log.info("搜索结果:{}", hits[0].getSourceAsString());
        article = JSONObject.parseObject(hits[0].getSourceAsString(), Article.class);
    }else{
        log.info("没有查询到数据");
        return;
    }
    article.setContent("更新测试_"+article.getContent());
    article.setTitle("更新测试_"+article.getTitle());
    System.out.println("===================更新数据=========================");
    Boolean updateResult = commodityServiceImpl.updateDoc(article, id);
    log.info("更新数据结果:{}",updateResult);

    //暂停五秒,等待数据更新之后再查询
    try {
        Thread.sleep(5*1000L);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("===================使用id查询数据,确认是否更新成功=========================");
    SearchHit[] find_hits = commodityServiceImpl.findById(Article.class, id);
    log.info("更新操作后查询到的数据:{}",find_hits);

}

/**
 * 批量更新测试
 */
@Test
public void updateMultiDoc(){
    //先搜索一批文档
    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);
    Article article;
    String id;
    ArrayList<HashMap<String, Object>> list = new ArrayList<>(16);
    if(hits.length>=1){
        int index = 1;
        for (SearchHit hit : hits) {
            HashMap<String, Object> map = new HashMap<>(4);
            id = hit.getId();
            article = JSONObject.parseObject(hit.getSourceAsString(), Article.class);
            article.setContent("批量更新测试_"+index+article.getContent());
            article.setTitle("批量更新测试_"+index+article.getTitle());
            map.put("id", id);
            map.put("obj", article);
            list.add(map);
            index++;
        }
    }else{
        log.info("没有查询到数据");
        return;
    }
    System.out.println("===================批量更新数据=========================");
    commodityServiceImpl.updateMultiDoc(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);
    log.info("更新操作后查询到的数据:{}", JSONArray.toJSONString(find_hits));
}


运行单个文档更新测试,日志:

===================只查询一条数据=========================
2019-09-21 15:25:26.046  INFO 281320 --- [           main] c.z.e.service.impl.ServiceImpl           : fieldName.length:1,fieldName:[content]
2019-09-21 15:25:26.332  INFO 281320 --- [           main] c.z.e.ElasticsearchDemoApplicationTests  : id:LzODT20Bk6nS0BLhTTX_
2019-09-21 15:25:26.340  INFO 281320 --- [           main] c.z.e.ElasticsearchDemoApplicationTests  : 搜索结果:{"content":"风住尘香花已尽,日晚倦梳头。物是人非事事休,欲语泪先流。\n闻说双溪春尚好,也拟泛轻舟。只恐双溪舴艋舟,载不动许多愁。测试寻寻觅觅咏梅.测试咏梅","create_time":1568997067851,"title":"武陵春·春晚"}
===================更新数据=========================
2019-09-21 15:25:26.506  INFO 281320 --- [           main] c.z.e.ElasticsearchDemoApplicationTests  : 更新数据结果:true
===================使用id查询数据,确认是否更新成功=========================
2019-09-21 15:25:31.515  INFO 281320 --- [           main] c.z.e.ElasticsearchDemoApplicationTests  : 更新操作后查询到的数据:{
  "_index" : "article",
  "_type" : "_doc",
  "_id" : "LzODT20Bk6nS0BLhTTX_",
  "_score" : 1.0,
  "_source" : {
    "content" : "更新测试_风住尘香花已尽,日晚倦梳头。物是人非事事休,欲语泪先流。\n闻说双溪春尚好,也拟泛轻舟。只恐双溪舴艋舟,载不动许多愁。测试寻寻觅觅咏梅.测试咏梅",
    "create_time" : 1568997067851,
    "title" : "更新测试_武陵春·春晚"
  }
}

运行批量更新测试,日志:

===================查询数据=========================
2019-09-21 15:28:48.077  INFO 280564 --- [           main] c.z.e.service.impl.ServiceImpl           : fieldName.length:1,fieldName:[content]
2019-09-21 15:28:49.308  INFO 280564 --- [           main] c.z.e.ElasticsearchDemoApplicationTests  : hits的数量:3
===================批量更新数据=========================
2019-09-21 15:28:49.491  INFO 280564 --- [           main] c.z.e.service.impl.ServiceImpl           : {"fragment":false,"id":"-jW4Um0Bk6nS0BLh5kJH","index":"article","primaryTerm":1,"result":"UPDATED","seqNo":11,"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":2}
2019-09-21 15:28:49.491  INFO 280564 --- [           main] c.z.e.service.impl.ServiceImpl           : 更新成功
2019-09-21 15:28:49.491  INFO 280564 --- [           main] c.z.e.service.impl.ServiceImpl           : {"fragment":false,"id":"_TW4Um0Bk6nS0BLh5kKL","index":"article","primaryTerm":1,"result":"UPDATED","seqNo":12,"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":2}
2019-09-21 15:28:49.491  INFO 280564 --- [           main] c.z.e.service.impl.ServiceImpl           : 更新成功
2019-09-21 15:28:49.492  INFO 280564 --- [           main] c.z.e.service.impl.ServiceImpl           : {"fragment":false,"id":"LzODT20Bk6nS0BLhTTX_","index":"article","primaryTerm":1,"result":"UPDATED","seqNo":13,"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":4}
2019-09-21 15:28:49.492  INFO 280564 --- [           main] c.z.e.service.impl.ServiceImpl           : 更新成功
===================再次查询数据,确认批量更新是否成功=========================
2019-09-21 15:28:54.492  INFO 280564 --- [           main] c.z.e.service.impl.ServiceImpl           : fieldName.length:1,fieldName:[content]
2019-09-21 15:28:54.495  INFO 280564 --- [           main] c.z.e.ElasticsearchDemoApplicationTests  : find_hits的数量:3
2019-09-21 15:28:54.506  INFO 280564 --- [           main] c.z.e.ElasticsearchDemoApplicationTests  : 更新操作后查询到的数据:[{"fields":{},"fragment":false,"highlightFields":{},"id":"-jW4Um0Bk6nS0BLh5kJH","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":0.59859395,"seqNo":-2,"sortValues":[],"sourceAsMap":{"create_time":1569050911977,"title":"批量更新测试_1武陵春·春晚","content":"批量更新测试_1风住尘香花已尽,日晚倦梳头。物是人非事事休,欲语泪先流。\n闻说双溪春尚好,也拟泛轻舟。只恐双溪舴艋舟,载不动许多愁。测试寻寻觅觅咏梅.测试咏梅"},"sourceAsString":"{\"content\":\"批量更新测试_1风住尘香花已尽,日晚倦梳头。物是人非事事休,欲语泪先流。\\n闻说双溪春尚好,也拟泛轻舟。只恐双溪舴艋舟,载不动许多愁。测试寻寻觅觅咏梅.测试咏梅\",\"create_time\":1569050911977,\"title\":\"批量更新测试_1武陵春·春晚\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"_TW4Um0Bk6nS0BLh5kKL","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":0.59859395,"seqNo":-2,"sortValues":[],"sourceAsMap":{"create_time":1569050911977,"title":"批量更新测试_2武陵春·春晚","content":"批量更新测试_2风住尘香花已尽,日晚倦梳头。物是人非事事休,欲语泪先流。\n闻说双溪春尚好,也拟泛轻舟。只恐双溪舴艋舟,载不动许多愁。测试寻寻觅觅咏梅.测试咏梅"},"sourceAsString":"{\"content\":\"批量更新测试_2风住尘香花已尽,日晚倦梳头。物是人非事事休,欲语泪先流。\\n闻说双溪春尚好,也拟泛轻舟。只恐双溪舴艋舟,载不动许多愁。测试寻寻觅觅咏梅.测试咏梅\",\"create_time\":1569050911977,\"title\":\"批量更新测试_2武陵春·春晚\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1},{"fields":{},"fragment":false,"highlightFields":{},"id":"LzODT20Bk6nS0BLhTTX_","matchedQueries":[],"primaryTerm":0,"rawSortValues":[],"score":0.5617394,"seqNo":-2,"sortValues":[],"sourceAsMap":{"create_time":1568997067851,"title":"批量更新测试_3批量更新测试_1更新测试_武陵春·春晚","content":"批量更新测试_3批量更新测试_1更新测试_风住尘香花已尽,日晚倦梳头。物是人非事事休,欲语泪先流。\n闻说双溪春尚好,也拟泛轻舟。只恐双溪舴艋舟,载不动许多愁。测试寻寻觅觅咏梅.测试咏梅"},"sourceAsString":"{\"content\":\"批量更新测试_3批量更新测试_1更新测试_风住尘香花已尽,日晚倦梳头。物是人非事事休,欲语泪先流。\\n闻说双溪春尚好,也拟泛轻舟。只恐双溪舴艋舟,载不动许多愁。测试寻寻觅觅咏梅.测试咏梅\",\"create_time\":1568997067851,\"title\":\"批量更新测试_3批量更新测试_1更新测试_武陵春·春晚\"}","sourceRef":{"fragment":true},"type":"_doc","version":-1}]

更新和批量更新都很简单

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

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