Elasticsearch Data Migration

本文介绍了如何利用JavaAPI进行Elasticsearch的数据迁移,包括获取客户端连接、迁移方法实现以及测试过程。重点在于通过合理设置参数,确保在迁移大量数据时集群性能稳定,同时优化索引速度。

本文介绍ES的数据迁移方案:

 

由于ES更新速度比较快,很大程度上, 我们需要更新版本、插件、甚至更新分词器, 单纯的upgrade很有可能不能满足业务需求, 更坏的情况下, 可能需要重建索引。本文从Java API 的角度来介绍ES的数据迁移(或数据重新索引)。基于以下逻辑实现,个人已测试过2亿数据的迁移,可以放心使用。

 

1. 获取clientl连接。本文选择transportClient。

public class ClientUtil
{

    static Settings defaultSettings = ImmutableSettings.settingsBuilder().put("client.transport.sniff", false).put("client.transport.ping_timeout","10s").build(); //如果你的集群node数量是稳定的,那么最好关闭sniff。 同时, 将ping时间设置高于默认5s, 很大程序上可以解决No Node available exception.
 
    // 创建私有对象
    private static TransportClient targetClient;
    
    private static TransportClient sourceClient;
 
    static {
        try {
            Class<?> clazz = Class.forName(TransportClient.class.getName());
            Constructor<?> constructor = clazz.getDeclaredConstructor(Settings.class);
            constructor.setAccessible(true);
		    Settings finalSettings = ImmutableSettings.settingsBuilder()
		                .put(defaultSettings)
		                .build();
		    targetClient = (TransportClient) constructor.newInstance(finalSettings);
		    targetClient.addTransportAddress(new InetSocketTransportAddress("192.168.1.100", 9300))
		    			.addTransportAddress(new InetSocketTransportAddress("192.168.1.101", 9300));
		    sourceClient = (TransportClient) constructor.newInstance(finalSettings);
		    sourceClient.addTransportAddress(new InetSocketTransportAddress("192.168.1.110", 9300))
		                .addTransportAddress(new InetSocketTransportAddress("192.168.1.111", 9300));
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
 
    // 取得源实例
    public static synchronized Client getSourceTransportClient() {
        return sourceClient;
    }
    
    // 取得目标实例
    public static synchronized Client getTargetTransportClient() {
        return targetClient;
    }

}

 

以上代码用于获取源cluster和目标cluster的client.

 

2.迁移主方法:

private void doMigrate(Client sourceclient, Client targetclient, String sourceIndexName, String targetIndexName, String indexDocType, int pageSize)
	{
		int total = 0;
		SearchResponse searchResponse = sourceclient.prepareSearch(sourceIndexName).setSearchType(SearchType.SCAN)
				.setQuery(matchAllQuery()).setSize(pageSize).setScroll(TimeValue.timeValueSeconds(20)).execute()
				.actionGet(); //scroll 的time不能太大, 以免对集群造成负载
		boolean exists = targetclient.admin().indices().prepareExists(targetIndexName).execute().actionGet().isExists();
		if (!exists)
			targetclient
					.admin()
					.indices()
					.prepareCreate(targetIndexName)
					.setSettings(
							settingsBuilder().put("index.number_of_replicas", 0).put("index.refresh_interval", "-1"))
					.execute().actionGet(); //设置replica为0, 不refresh, 为了提高索引速度。
		try
		{
			Thread.sleep(200);
		} catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		BulkProcessor bulkProcessor = BulkProcessor.builder(targetclient, new BulkProcessor.Listener()
		{

			@Override
			public void beforeBulk(long executionId, BulkRequest request)
			{

			}

			@Override
			public void afterBulk(long executionId, BulkRequest request, BulkResponse response)
			{
				if (response.hasFailures())
				{
					throw new RuntimeException("BulkResponse show failures: " + response.buildFailureMessage());
				}
			}

			@Override
			public void afterBulk(long executionId, BulkRequest request, Throwable failure)
			{
				throw new RuntimeException("Caught exception in bulk: " + request + ", failure: " + failure, failure);
			}
		}).setConcurrentRequests(10).build(); //设置线程数量, 大小可以根据自己机器调配。

		while (true)
		{
			searchResponse = sourceclient.prepareSearchScroll(searchResponse.getScrollId())
					.setScroll(TimeValue.timeValueSeconds(20)).execute().actionGet();
			for (SearchHit hit : searchResponse.getHits())
			{

				IndexRequestBuilder indexRequestBuilder = targetclient.prepareIndex(targetIndexName, indexDocType);
				indexRequestBuilder.setSource(hit.getSource());
				indexRequestBuilder.setId(hit.getId());
				indexRequestBuilder.setOpType(IndexRequest.OpType.INDEX);
				bulkProcessor.add(indexRequestBuilder.request());
				total++;
			}
			System.out.println("Already migrated : " + total + " records!");
			if (searchResponse.getHits().hits().length == 0)
			{
				break;
			}
		}
		try
		{
			Thread.sleep(10000);//Sleep 10s waiting the cluster.
		} catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		bulkProcessor.close();
		targetclient
		.admin()
		.indices().prepareUpdateSettings(targetIndexName).setSettings(
				settingsBuilder().put("index.number_of_replicas", 1).put("index.refresh_interval", "1s"))
		.execute().actionGet();
	}

 

 3.测试:

public static void main(String[] args) throws ElasticSearchException, IOException, InterruptedException
	{
		int pageSize = 40; //分页大小, 不能过大, 太大影响集群性能, 可能引起no node 异常。
		Client sourceclient = ClientUtil.getSourceTransportClient();
		Client targetclient = ClientUtil.getTargetTransportClient();
	        //调用doMigrate方法。 doMigrate(sourceclient, targetclient, "test", "testnew", "test", pageSize);}
2025.09.01 17:01:05 INFO app[][o.s.a.AppFileSystem] Cleaning or creating temp directory D:\sonarqube-25.8.0.112029\temp 2025.09.01 17:01:05 INFO app[][o.s.a.es.EsSettings] Elasticsearch listening on [HTTP: 127.0.0.1:9001, TCP: 127.0.0.1:{}] 2025.09.01 17:01:05 INFO app[][o.s.a.ProcessLauncherImpl] Launch process[ELASTICSEARCH] from [D:\sonarqube-25.8.0.112029\elasticsearch]: C:\Program Files\Java\jdk-17\bin\java -Xms4m -Xmx64m -XX:+UseSerialGC -Dcli.name=server -Dcli.script=./bin/elasticsearch -Dcli.libs=lib/tools/server-cli -Des.path.home=D:\sonarqube-25.8.0.112029\elasticsearch -Des.path.conf=D:\sonarqube-25.8.0.112029\temp\conf\es -Des.distribution.type=tar -cp D:\sonarqube-25.8.0.112029\elasticsearch\lib\*;D:\sonarqube-25.8.0.112029\elasticsearch\lib\cli-launcher\* org.elasticsearch.launcher.CliToolLauncher 2025.09.01 17:01:05 INFO app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running 2025.09.01 17:01:16 INFO app[][o.s.a.SchedulerImpl] Process[es] is up 2025.09.01 17:01:16 INFO app[][o.s.a.ProcessLauncherImpl] Launch process[WEB_SERVER] from [D:\sonarqube-25.8.0.112029]: C:\Program Files\Java\jdk-17\bin\java -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djava.io.tmpdir=D:\sonarqube-25.8.0.112029\temp -XX:-OmitStackTraceInFastThrow --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED --add-exports=java.base/jdk.internal.ref=ALL-UNNAMED --add-opens=java.base/java.nio=ALL-UNNAMED --add-opens=java.base/sun.nio.ch=ALL-UNNAMED --add-opens=java.management/sun.management=ALL-UNNAMED --add-opens=jdk.management/com.sun.management.internal=ALL-UNNAMED -Xms1g -Xmx1g -XX:+HeapDumpOnOutOfMemoryError -Dhttp.nonProxyHosts=localhost|127.*|[::1] -cp ./lib/sonar-application-25.8.0.112029.jar;D:\sonarqube-25.8.0.112029\lib\jdbc\postgresql\postgresql-42.7.7.jar org.sonar.server.app.WebServer D:\sonarqube-25.8.0.112029\temp\sq-process7484978067730404954properties 2025.09.01 17:01:19 INFO app[][o.s.a.SchedulerImpl] Process[Web Server] is stopped 2025.09.01 17:01:20 INFO app[][o.s.a.SchedulerImpl] Process[ElasticSearch] is stopped 2025.09.01 17:01:20 INFO app[][o.s.a.SchedulerImpl] SonarQube is stopped 已设配置sonar.jdbc.url=jdbc:postgresql://localhost/sonar?currentSchema=public #sonar表示数据库名称 sonar.host.url=http://localhost:9000 /sonarqube sonar.jdbc.username=sonar #数据库用户名 sonar.jdbc.password=123456 #数据库密码 sonar.login=admin #登陆sonarqube的账号 sonar.password=Sun.12345678 #登陆sonarqube的密码 sonar.search.javaOpts=-Xms1g -Xmx1g -XX:+UseG1GC -Des.bootstrap.mlockall=false sonar.web.javaOpts=-Xms1g -Xmx1g -XX:+HeapDumpOnOutOfMemoryError sonar.ce.javaOpts=-Xms1g -Xmx1g -XX:+HeapDumpOnOutOfMemoryError sonar.search.javaAdditionalOpts=-XX:MaxGCPauseMillis=200 -XX:+UseG1GC -XX:MaxDirectMemorySize=1g
最新发布
09-02
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值