es~批量更新bulkIndex和bulkUpdate


重要说明

  • bulkIndex 批量索引文档更新,文档不存在就建立,存在就覆盖,如果文档原来有3个字段,批量更新时有2个字段,在bulkIndex之后,它最后会变成最新的2个字段
  • bulkUpdate 批量更新文档字段,如果文档原来有3个字段,批量更新时有2个字段,结果还是3个字段

依赖添加

    
        1.2.68
        6.5.4
        6.8.7
    
    
     
          org.springframework.boot
          spring-boot-starter-data-elasticsearch
      
      
          org.springframework.boot
          spring-boot-starter-web
      
      
          org.elasticsearch.client
          elasticsearch-rest-high-level-client
          ${elasticsearch.high.version}
      
      
          org.elasticsearch
          elasticsearch
          ${elasticsearch.client.version}
      
  

bulkIndex实例

    /**
     * 批量替换,不存在就建立,存在就替换,原字段会删除,新字段会添加
     *
     * @throws JsonProcessingException
     */
    @Test
    public void bulkIndex() throws JsonProcessingException {
        List queries = new ArrayList<>();

        IndexQuery indexQuery = new IndexQuery();
        indexQuery.setId("552625903956398080");
        Map sourceMap = new HashMap<>();
        sourceMap.put("name", "xx1");
        indexQuery.setSource(new ObjectMapper().writeValueAsString(sourceMap));
        indexQuery.setType("esdto");
        indexQuery.setIndexName("esdto");
        queries.add(indexQuery);

        indexQuery = new IndexQuery();
        indexQuery.setId("552306605039816704");
        sourceMap = new HashMap<>();
        sourceMap.put("name", "xx2");
        indexQuery.setSource(new ObjectMapper().writeValueAsString(sourceMap));
        indexQuery.setType("esdto");
        indexQuery.setIndexName("esdto");
        queries.add(indexQuery);

        elasticsearchTemplate.bulkIndex(queries,
                BulkOptions.builder().withTimeout(TimeValue.MINUS_ONE).build());
    }

bulkUpdate实例

   /**
     * 批量更新某些字段.
     *
     * @throws JsonProcessingException
     */
    @Test
    public void bulkUpdate() throws JsonProcessingException {
        List updateQueries = new ArrayList<>();

        Map sourceMap = new HashMap<>();
        sourceMap.put("name", "xx3");
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.doc(sourceMap);
        UpdateQuery updateQuery = new UpdateQueryBuilder()
                .withId("552629576220545024")
                .withIndexName("esdto")
                .withType("esdto")
                .withUpdateRequest(updateRequest)
                .build();
        updateQueries.add(updateQuery);


        sourceMap = new HashMap<>();
        sourceMap.put("name", "xx4");
        updateRequest = new UpdateRequest();
        updateRequest.doc(sourceMap);
        updateQuery = new UpdateQueryBuilder()
                .withId("552629636035514368")
                .withIndexName("esdto")
                .withType("esdto")
                .withUpdateRequest(updateRequest)
                .build();
        updateQueries.add(updateQuery);

        elasticsearchTemplate.bulkUpdate(updateQueries);
    }