先上官方示例代码:官方示例
Java代码:
// 批量插入数据
public void InsertBatch() {
try {
// 设置集群名称
Settings settings = Settings.builder().put("cluster.name", "my-es-analyze").build();
// 创建client
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.33.5"), 9300))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.33.50"), 9300)); /* 批量操作开始 */
BulkRequestBuilder bulkRequest = client.prepareBulk(); InsertDomain insertDomain = null;
String json = null; // 读取数据源 excel/mysql等
List<List<String>> list = "你的数据源"; if (list != null) {
System.out.println("开始批量插入");
for (int i = 0; i < list.size(); i++) { // 数据读取(略)根据自已的业务进行。
json = JSONUtils.toJSON(inputDomain); //转Json
bulkRequest.add(client.prepareIndex("index", "type").setSource(json)); //每一千条提交一次
if (i % 1000 == 0) {
bulkRequest.execute().actionGet();
System.out.println("提交了:" + i);
} }
bulkRequest.execute().actionGet();
System.out.println("批量插入完毕");
}
/* 批量操作结束 */ // 关闭client
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}