欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > Spring集成ES

Spring集成ES

2025/2/25 12:29:44 来源:https://blog.csdn.net/qq_55630615/article/details/140726124  浏览:    关键词:Spring集成ES

RestAPI

ES官方提供的java语言客户端用以组装DSL语句,再通过http请求发送给ES

RestClient初始化

引入依赖

<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
初始化RestHighLevelClient
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.150.101:9200")
));

RestClient操作索引

创建索引

创建一个CreateIndexRequest对象

在对象中添加JSON格式的Mapping映射参数

client.indices()方法会返回封装了所有索引库操作的一个客户端

这里我们使用

client.indices().create(request, RequestOptions.DEFAULT);

删除索引

创建一个DeleteIndexRequest对象

调用delete方法

client.indices().delete(request, RequestOptions.DEFAULT);

查询索引是否存在

创建一个GetIndexRequest对象

调用exist方法

client.indices().exists(request, RequestOptions.DEFAULT);

RestClient操作文档

查询文档

创建一个GetRequest对象

调用get方法

 GetResponse response = client.get(request, RequestOptions.DEFAULT);String json = response.getSourceAsString();

删除文档

创建一个DeleteRequest对象

调用delete方法

client.delete(request, RequestOptions.DEFAULT);

修改文档

如果id存在就修改

如果id不存在就新增

创建一个 UpdateRequest对象

调用update方法

client.update(request, RequestOptions.DEFAULT);

批量导入文档

创建BulkRequest对象,可以添加以下请求

  • IndexRequest,也就是新增
  • UpdateRequest,也就是修改
  • DeleteRequest,也就是删除

在对象中添加多个不同请求,最后调用bulk方法

request.add(new IndexRequest("items").id("1").source("json doc1", XContentType.JSON));request.add(new IndexRequest("items").id("2").source("json doc2", XContentType.JSON));
client.bulk(request, RequestOptions.DEFAULT);

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词