0%

elasticsearch-java客户端

连接客户端

// 方法1
@Bean
public RestHighLevelClient restHighLevelClient() {
    ClientConfiguration clientConfiguration = ClientConfiguration.builder()
            .connectedTo("192.168.3.17:9200", "192.168.3.19:9200", "192.168.3.20:9200")
            .withBasicAuth("elastic", "elastic")
            .build();
    return RestClients.create(clientConfiguration).rest();
}
// 方法2
@Bean
public RestHighLevelClient restHighLevelClient() {
    RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
            RestClient.builder(
                    new HttpHost("192.168.3.17", 9200, "http"),
                    new HttpHost("192.168.3.19", 9200, "http"),
                    new HttpHost("192.168.3.20", 9200, "http")
            )
    );
    return restHighLevelClient;
}
// 方法3
// 无需密码的连接
@Bean
public RestHighLevelClient restHighLevelClient() {
    return new RestHighLevelClient(RestClient.builder(new HttpHost[]{
            new HttpHost("localhost", 9200, "http")
    }));
}

发送文档

// 单条发送
IndexRequest request = new IndexRequest(indexName);
User user = new User(RandomStringUtils.randomAlphanumeric(50), 20 + new Random().nextInt(30));
request.source(JSON.toJSONString(user), XContentType.JSON);
try {
    restHighLevelClient.index(request, RequestOptions.DEFAULT);
} catch (IOException e) {
}

// 批量发送
BulkRequest requests = new BulkRequest();
for (int j = 0; j < 100; j++) {
    User user = new User(RandomStringUtils.randomAlphanumeric(50), 20 + new Random().nextInt(30));
    IndexRequest request = new IndexRequest(indexName);
    request.source(JSON.toJSONString(user), XContentType.JSON);
    requests.add(request);
}
try {
    restHighLevelClient.bulk(requests, RequestOptions.DEFAULT);
} catch (IOException e) {
}