1、介绍
Elasticsearch是一个基于Lucene构建的开源搜索引擎,支持复杂的搜索功能。Java API SDK是Elasticsearch官方提供的一种方式,允许Java应用程序直接与Elasticsearch集群交互。8.x的版本和旧版本API差别比较大。本文没有使用Springboot data相关的功能,而是直接演示原生API的用法。
2、引入依赖
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.7.1</version>
</dependency>
</dependencies>
3、创建和关闭连接
void testAnonymous() {
// 匿名连接
RestClient restClient = RestClient.builder(new HttpHost("192.168.0.10", 9200),
new HttpHost("192.168.0.11", 9200),
new HttpHost("192.168.0.12", 9200)).build();
ObjectMapper objectMapper = new ObjectMapper();
RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper(objectMapper));
ElasticsearchClient client = new ElasticsearchClient(transport);
client.shutdown();
}
void testBasicCredentials() {
// 使用账号密码创建连接
String username = "elastic";
String password = "elastic";
final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200))
.setHttpClientConfigCallback(httpAsyncClientBuilder ->
httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
client.shutdown();
}