java中使用es入门

java中使用es

es的java驱动包,在不同的版本中会有不同的兼容性问题,所以在使用时一定要注意依赖的版本,这里笔者采用的是官网最新的6.2.3版本。

依赖


    org.elasticsearch.client
    transport
    6.2.3


    org.elasticsearch
    elasticsearch
    6.2.3

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 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());
            }
        }
    }
    

你可能感兴趣的:(java中使用es入门)