irpas技术客

ElasticSearch JavaAPI(java操作)_dexi.Chi 程序猿_elasticsearch java

网络投稿 2805

操作ElasticSearch分为脚本操作(运维人员常用)和java操作(开发人员常用),今天小编主要介绍java操作方式,之前小编讲解了ES如何搭建,并介绍了IK分词器,今天基于ES环境来继续学习。

需求:使用sringboot整合ElasticSearch实现步骤: 1、 搭建springboot工程 2、 引入ElasticSearch相关坐标 3、 测试编码 下面是ElasticSearch的相关坐标 开始部署springboot项目 由于不是web工程,下面页面不需要勾选 直接finish完成 去pom文件引入ES所需要的坐标 <!-- 引入ES的坐标 --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.4.0</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>7.4.0</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.4.0</version> </dependency>

写一个测试类,并启动下 这个时候我们开始整合springboot 在resource下创建application.yml 在java层级下创建ElasticSearchConfig类

package com.itheima.elasticsearchdemo.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @ConfigurationProperties(prefix = "elasticsearch") public class ElasticSearchConfig { private String host; private int port; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } @Bean public RestHighLevelClient client(){ return new RestHighLevelClient(RestClient.builder( new HttpHost( host,port,"http" ) )); } }

上方出现红条没有问题,引入一个maven坐标即可解决 重新修改测试类

package com.itheima.elasticsearchdemo; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ElasticsearchDemoApplicationTests { @Autowired private RestHighLevelClient client; @Test void contextLoads() { //1.创建ES客户端对象 // RestHighLevelClient client = new RestHighLevelClient(RestClient.builder( // new HttpHost( // "192.168.149.135",9200,"http" // ) // )); System.out.println(client); } }

启动下 发现没有问题,整合完毕

操作索引添加索引 执行完进行查询 添加索引及映射信息 执行成功后,去kibana看下 查询索引 这样查询 是itcast:后面显示个对象 我们要向查询数据可以改为 再查询一下 删除索引 执行一下 判断索引是否存在 执行一下 操作文档 添加文档(map的数据形式) 查询一下 以上是map的数据形式,建议改成实体类型的入参添加文档(实体的数据形式 实体转json) 修改文档 添加文档时id存在时修改,id不存在则是添加,就是上面的添加操作根据id查询文档 执行一下 删除文档 执行一下,打印删除为1的id


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #ElasticSearch #JAVA