添加 Maven 依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.7.1</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.7.1</version>
</dependency>
初始化客户端配置
@Bean
public RestHighLevelClient restHighLevelClient() {
RestClientBuilder builder = RestClient.builder(this.getHosts());
return new RestHighLevelClient(builder);
}
private HttpHost[] getHosts() {
String[] httpHosts = uris.split(",");
return Arrays.stream(httpHosts).map(item -> {
String[] nodes = item.split(":");
return new HttpHost(nodes[0], Integer.parseInt(nodes[1]));
}).toArray(HttpHost[]::new);
}
spring.elasticsearch.uris=150.158.148.77:9200,150.158.148.78:9200,150.158.148.79:9200
查询数据
@Autowired
private RestHighLevelClient client;
@Test
void searchTest() throws IOException {
SearchRequest searchRequest = new SearchRequest("index-test");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery("username", "tommy"));
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
RestStatus status = searchResponse.status();
TimeValue took = searchResponse.getTook();
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit searchHit : searchHits) {
String sourceAsString = searchHit.getSourceAsString();
System.out.println(sourceAsString);
}
}