java 連接 Elasticsearch 使用 RestHighLevelClient進行批量增加、刪除、修改


依賴

<!-- elasticsearch-rest-client -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>7.13.3</version>
</dependency>
<!-- elasticsearch-rest-high-level-client -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.13.3</version>
</dependency>

配置

@Configuration
public class ESConfig {

    @Bean
    public RestHighLevelClient getRestHighLevelClient(){
        HttpHost http1 = new HttpHost("127.0.0.1", 9200, "http");
        HttpHost http2 = new HttpHost("127.0.0.1", 9201, "http");
        RestClientBuilder restClientBuilder = RestClient.builder(http1, http2);
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);
        return restHighLevelClient;
    }

}
@Autowired
private RestHighLevelClient restHighLevelClient;

批量增/刪/改

public void bulkQuery() throws IOException {
    IndexRequest indexRequest2 = new IndexRequest("myindex");
	indexRequest2.id("2");

    IndexRequest indexRequest4 = new IndexRequest("myindex");
	indexRequest4.id("4");

    BulkRequest bulkRequest = new BulkRequest();
	bulkRequest.add(indexRequest2).add(indexRequest4);

    BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
    for (BulkItemResponse bulkItemResponse : bulkResponse) {
        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;
        }
    }
}


免責聲明!

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



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