RestAPI

官方文档链接

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);

  • 14
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值