java中使用es入门
2019-02-13 本文已影响0人
f22448cd5541
java中使用es
es的java驱动包,在不同的版本中会有不同的兼容性问题,所以在使用时一定要注意依赖的版本,这里笔者采用的是官网最新的6.2.3
版本。
依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.2.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.2.3</version>
</dependency>
Demo例子
-
创建
TransportClient
类:# 这里默认配置一个es的集群名字 Settings settings = Settings.builder() .put("cluster.name", "my-application").build(); TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9301)) .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
-
在索引下插入数据
Map data = new HashMap<>(); data.put("test", "test log"); data.put("time", System.currentTimeMillis()); IndexResponse response = client.prepareIndex("test", "log", UUID.randomUUID().toString()).setSource(data).get(); System.out.println("id: "+response.getId());
-
批量插入数据
public void batchInsert(List<JSONObject> list) { if (list.size() > 0) { BulkRequestBuilder prepareBulk = client.prepareBulk(); for (JSONObject jsonObject : list) { prepareBulk.add(client.prepareIndex(INDEX, TYPE, UUID.randomUUID().toString()).setSource(jsonObject)); } BulkResponse bulkResponse = prepareBulk.get(); RestStatus status = bulkResponse.status(); if (status.getStatus() == 200) { logger.warn("[add] - batch add log fail, statue: {}, data: {}", status, JSON.toJSON(list).toString()); } } }