springboot使用RestHighLevelClient批量插入


1、引入maven(注意版本要一致

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.4.3</version>
        </dependency>   

2、配置.properties

spring.elasticsearch.rest.uris=http://127.0.0.1:9200
spring.elasticsearch.rest.password=
spring.elasticsearch.rest.username=

3、使 @Autowired

private RestHighLevelClient restHighLevelClient; private void bulkPutIndex(List<Map<String, Object>> list ) throws IOException { if (JudgeUtil.isEmpty(list)){ return; } String index = "test"; String type = "test"; int size = list.size(); BulkRequest request = new BulkRequest(); for (int i = 0; i < size; i++) { Map<String, Object> map = list.get(i);        //這里必須每次都使用new IndexRequest(index,type),不然只會插入最后一條記錄(這樣插入不會覆蓋已經存在的Id,也就是不能更新)
       //request.add(new IndexRequest(index,type).opType("create").id(map.remove("id").toString()).source(map));
        
request.add(new IndexRequest(index, type, String.valueOf(map.remove("id"))).source(map,XContentType.JSON));

    
      restHighLevelClient.bulk(request); 

  } 
}

 參考地址:https://www.cnblogs.com/leeSmall/p/9218779.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM