官方文档
找到原生的依赖<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elaseicsearch-rest-high-level-client</artifactId> <version>7.6.2</version> </dependency>
找对象 分析类中的方法即可配置基本的项目
创建一个空项目从头搭建熟悉流程
创建一个新模块使用springboot,勾选 修改项目设置将jdk调成1.8下载对应依赖,依赖真的下了好久好久啊,怀疑人生,查看对应依赖找到对应es依赖 发现springboot2.2.6中依赖的es为6.8.2的版本与我们使用的最新版本7.6.2不同,将其依赖修改(一定要保证我们导入的依赖与我们使用的版本一致) 修改成功 配置对应esclient配置到bean中
package com.lixiaolang.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ElasticSearchClientConfig { @Bean public RestHighLevelClient restHighLevelClient(){ RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http") ) ); return client; } }进行测试
package com.lixiaolang; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.io.IOException; @SpringBootTest class EsApiApplicationTests { @Autowired private RestHighLevelClient restHighLevelClient; //测试索引的创建 PUT lixiaolang_index索引 @Test void contextLoads() throws IOException { //1. 创建索引请求 CreateIndexRequest request = new CreateIndexRequest("lixiaolang_index"); //2. 客户端执行创建请求,请求后获得响应 CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT); System.out.println(createIndexResponse); } }启动es服务后测试 运行结果拿到该对象,在head中查看发现索引被创建成功 同样的可以获取索引,如下 删除同理,不过删除返回的对象为AcknowledgedResponse对象,具体细节方法自行查阅源码。
下面开始文档有关的操作,先创建一个实体类User以供测试 如插入数据
//测试添加文档 @Test void addDocument() throws IOException { //创建对象 User user = new User("李小狼", 18); //创建请求 IndexRequest request = new IndexRequest("lixiaolang_index"); //之前的规则 put /lixiaolang_index/_doc/1 request.id("1"); request.timeout(TimeValue.timeValueSeconds(1)); //将我们的数据放入请求 json(记得导入阿里巴巴的fastjson) request.source(JSON.toJSONString(user), XContentType.JSON); //客户端发送请求, 获取响应结果 IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT); System.out.println(indexResponse.toString()); System.out.println(indexResponse.status()); }输出结果 created即创建文档成功