将ElasticSearch的数据批量导入至MySQL

该博客介绍了如何将ElasticSearch中的数据批量导入到MySQL数据库。首先,通过引入相关依赖,创建ElasticSearch客户端并使用scroll API获取所有数据。然后,数据经过转换后,利用MySQL JDBC连接插入到指定表中。整个过程涉及ElasticSearch的搜索操作和MySQL的SQL执行,实现了数据迁移。

将ElasticSearch的数据批量导入至MySQL

导入Jar包

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.14.0</version>
</dependency>

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

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.28</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.22</version>
</dependency>

Elastic的操作类

public class ElasticCustomClient {

    RestHighLevelClient restHighLevelClient = null;

    public void createClient() {
        restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1", 9200),
                        new HttpHost("127.0.0.1", 9300),
                        new HttpHost("127.0.0.1", 9400))
        );
    }

    public List<String> scrollData(String index) {
        try {
            createClient();
            String scrollId = "";
            List<String> result = new ArrayList<>();
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices(index);
            searchRequest.scroll("1m");
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();
            for (int i = 0; i < hits.getHits().length; i++) {
                result.add(hits.getHits()[i].getSourceAsString());
            }
            //记录滚动ID
            scrollId = response.getScrollId();

            while (true) {
                if (scrollId == null || scrollId.equals("")) {
                    break;
                }
                SearchScrollRequest searchScrollRequest = new SearchScrollRequest(scrollId).scroll(TimeValue.timeValueMinutes(1));
                response = restHighLevelClient.scroll(searchScrollRequest, RequestOptions.DEFAULT);
                if (response != null && response.getHits().getHits().length > 0) {
                    for (SearchHit hit : response.getHits().getHits()) {
           
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值