官方文档链接
Compatibility | Java REST Client [7.4] | Elastic
使用Java操作ES,准备工作
添加依赖坐标:关键是elasticsearch-rest-high-level-client。
修改配置文件:没有 跟es相关的配置,但是为了防止启动连接数据库不存在,先执行SQL脚本
把客户端连接对象放到IoC容器里。把以下代码加到引导类里,或者加到一个配置类里
@Bean
public RestHighLevelClient esClient(){
return new RestHighLevelClient(RestClient.builder(
new HttpHost("IP", 端口)
));
}
创建单元测试类,添加@SpringBootTest,再注入RestHighLevelClient对象
操作索引的API
//1. 创建索引
CreateIndexRequest request = new CreateIndexRequest("索引名")
.source("json字符串", XContentType.JSON);
esClient.indices().create(request, RequestOptions.DEFAULT);
//2. 删除索引
DeleteIndexRequest request = new DeleteIndexRequest("索引名");
esClient.indices().delete(request, RequestOptions.DEFAULT);
//3. 判断索引是否存在
GetIndexRequest request = new GetIndexRequest("索引名")
boolean exists = esClient.indices()
.exists(request, RequestOptions.DEFAULT);
操作文档的API
//1. 新增或修改
IndexRequest request = new IndexReuqest("索引名")
.id("文档唯一标识")
.source("文档json字符串", XContentType.JSON);
esClient.index(request, RequestOptions.DEFAULT);
//2. 查询
GetRequset request = new GetRequest("索引名").id("文档唯一标识");
GetResponse response = esClient.get(request, RequestOptions.DEFAULT);
String docJson = response.getSourceAsString();
//3. 删除
DeleteRequest request = new DeleteRequest("索引名").id("文档唯一标识");
esClient.delete(request, RequestOptions.DEFAULT);
//4. 批量操作:通常用于批量新增,也可以用于批量删除等写操作
BulkRequest bulkRequest = new BulkRequest("索引名");
for(Xxx xx: list){
//准备IndexRequest对象
IndexRequest request = new IndexRequest()
.id(xx.getId().toString())
.source(JSON.toJSONString(xx), XContentType.JSON);
//把IndexRequest添加到BulkRequest对象里
bulkRequest.add(request);
}
//最后一次性把BulkRequest里的数据存储到es里
esClient.bulk(bulkRequest, RequestOption.DEFAULT);