1、pom
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.9.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.json</artifactId>
<version>2.0.1</version>
</dependency>
2、Java客户端注入
我这里用的是apiKey验证的,也可以没有验证,或者上号密码验证
@Slf4j
@Configuration
public class ElasticSearchConfig {
@Value("${elasticsearch.server-url}")
private String serverUrl;
@Value("${elasticsearch.api-key}")
private String apiKey;
/**
* 注入IOC容器 apiKey注入(同步)
*/
@Bean
public ElasticsearchClient client() throws Exception {
File certFile = ResourceUtils.getFile("classpath:ch_http_ca.crt");
SSLContext sslContext = TransportUtils.sslContextFromHttpCaCrt(certFile);
// 用builder创建RestClient对象
RestClient client = RestClient.builder(HttpHost.create(serverUrl))
.setHttpClientConfigCallback(
hc -> hc.setSSLContext(sslContext).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE))
.setDefaultHeaders(new Header[] { new BasicHeader("Authorization", "ApiKey " + apiKey) })
.build();
ElasticsearchTransport transport =RestClientTransport(client, new JacksonJsonpMapper());
return new ElasticsearchClient(transport);
}
}
3、ElasticSearch操作示例
//创建索引
public String save() throws IOException {
CreateIndexResponse indexResponse = client.indices().create(c -> c.index("user"));
return "ok";
}
//获取索引
public String getIndex() throws IOException {
GetIndexResponse getIndexResponse = client.indices().get(i -> i.index("user"));
System.out.println(getIndexResponse.toString());
return getIndexResponse.toString();
}
//判断索引是否存在
public String existsTest() throws IOException {
BooleanResponse booleanResponse = client.indices().exists(e -> e.index("user"));
System.out.println(booleanResponse.value());
return "ok";
}
//删除索引
public String deleteTest() throws IOException {
DeleteIndexResponse deleteIndexResponse = client.indices().delete(d -> d.index("user"));
System.out.println(deleteIndexResponse.acknowledged());
return "ok";
}
//创建文档
public String createDoc() throws IOException {
Map<String, Object> doc = new HashMap<>();
doc.put("age", 30);
doc.put("name", "carlos");
CreateResponse response = client.create(builder -> builder.index("poems").id("1").document(doc));
log.info(response.toString());
}
//删除文档
public void deleteDoc() throws IOException {
DeleteResponse response = client.delete(builder -> builder.index("user").id("1"));
log.info(response.toString());
}
。。。。。。。。。。。。。。。。。。。。。。。。