主题
Java 客户端
Elasticsearch 提供官方 Java 客户端,方便 Java 应用程序与 Elasticsearch 集群进行交互,实现索引管理、文档操作和查询功能。
1. 客户端类型
- Rest High Level Client(HLRC):基于 REST 的高级客户端,提供丰富的 API(已逐步废弃)
- Java API Client:Elasticsearch 8.x 版本推出的新官方客户端,基于 Elasticsearch Java API
2. 引入依赖(Maven 示例)
xml
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.10.0</version>
</dependency>
3. 客户端初始化示例
java
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.ElasticsearchException;
import co.elastic.clients.elasticsearch.core.GetResponse;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
public class ElasticsearchExample {
public static void main(String[] args) throws Exception {
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200)).build();
RestClientTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 示例:获取文档
try {
GetResponse<Object> response = client.get(g -> g
.index("my-index")
.id("1"), Object.class);
if (response.found()) {
System.out.println(response.source());
} else {
System.out.println("Document not found");
}
} catch (ElasticsearchException e) {
e.printStackTrace();
}
restClient.close();
}
}
4. 常用操作
- 创建索引
- 添加、更新、删除文档
- 查询与聚合
- Bulk 批量操作
5. 注意事项
- 注意客户端版本与 Elasticsearch 集群版本兼容性
- 连接池和超时配置需根据业务调整
- 推荐使用官方最新 Java API Client,避免旧版被废弃风险
掌握 Elasticsearch Java 客户端的使用,有助于构建高效稳定的搜索与分析应用。