Springboot 操作Elasticsearch 方式二 【rest-high-level-client】
操作环境:win10+elasticsearch7.11.1 ,springboot2.1.8+elasticsearch6.7.1客户端
elasticsearch版本是向下兼容的,也就是elasticsearch安装的版本比较高,使用springboot连接ES时,版本低一些也是可以正常使用的
springboot集成ES,对应版本查询https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#preface.versions
整体目录结构
- pom.xml文件添加依赖
<properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring-boot.version>2.1.8.RELEASE</spring-boot.version> <elasticsearch.version>6.7.1</elasticsearch.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch --> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>${elasticsearch.version}</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>${elasticsearch.version}</version> </dependency> </dependencies>
- application.yml添加如下配置
server:
port: 8080
spring:
application:
name: resthighclient
#es http方式
elasticsearch:
hostname: 127.0.0.1
port: 9200
scheme: http
connTimeout: 1000
socketTimeout: 3000
connectionRequestTimeout: 500
username: elastic
password: 123456
- 创建连接配置类RestClientConfig
package com.example.resthighclient.config; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RestClientConfig { @Value("${elasticsearch.hostname}") private String hostname; @Value("${elasticsearch.port}") private int port; @Value("${elasticsearch.connTimeout}") private int connTimeout; @Value("${elasticsearch.socketTimeout}") private int socketTimeout; @Value("${elasticsearch.connectionRequestTimeout}") private int connectionRequestTimeout; @Value("${elasticsearch.username}") private String username; @Value("${elasticsearch.password}") private String password; /* HighLevelRestConfig */ @Bean(destroyMethod = "close", name = "client") public RestHighLevelClient restHighLevelClient(){ CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username,password)); RestClientBuilder builder = RestClient.builder(new HttpHost(hostname, port)) .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder .setConnectTimeout(connTimeout) .setSocketTimeout(socketTimeout) .setConnectionRequestTimeout(connectionRequestTimeout) ).setHttpClientConfigCallback(f->f.setDefaultCredentialsProvider(credentialsProvider));//带密码的ES连接访问 return new RestHighLevelClient(builder); } }
- 创建索引常量
package com.example.resthighclient.constant; public interface Constant { String INDEX = "book"; }
- 创建接口访问controller类
package com.example.resthighclient.controller; import com.alibaba.fastjson.JSON; import com.example.resthighclient.constant.Constant; import com.example.resthighclient.model.Book; import com.example.resthighclient.model.response.Result; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.MatchPhrasePrefixQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.io.IOException; import java.util.Date; import java.util.UUID; @RestController @RequestMapping("/api/high") @Slf4j public class HighLevelRestController { /** * logger */ private static final Logger logger = LoggerFactory.getLogger(HighLevelRestController.class); @Resource private RestHighLevelClient restHighLevelClient; /* 获取ES信息 */ @GetMapping("es") public Result getEsInfo() throws IOException { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); SearchRequest searchRequest = new SearchRequest(); searchRequest.source(searchSourceBuilder); //查询ES SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); return Result.SUCCESS(searchResponse); } //保存数据 @PostMapping("save") public Result save(@RequestBody Book book) throws IOException { if (book == null || StringUtils.isEmpty(book.getTitle())) { return Result.FAIL("标题不能为空"); } else if (StringUtils.isEmpty(book.getContent())) { return Result.FAIL("内容不能为空"); } UUID uuid= UUID.randomUUID(); book.setId(uuid.toString()); book.setCreateTime(new Date()); IndexRequest indexRequest = new IndexRequest(Constant.INDEX,"_doc","id") .id(book.getId()) .source(JSON.toJSONString(book), XContentType.JSON); IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); if (indexResponse.getId() != null) return Result.SUCCESS("保存成功"); else return Result.FAIL("保存失败"); } //判断索引是否存在 @GetMapping("isExist") public boolean isIndexExists(String index) throws IOException{ GetIndexRequest request = new GetIndexRequest(); request.indices(); request.local(false); request.humanReadable(true); boolean exists = restHighLevelClient.indices().exists(request,RequestOptions.DEFAULT) ; return exists; } /* 根据id查询 */ @GetMapping("getById") public Result getById(String id) throws IOException { GetRequest getRequest=new GetRequest(Constant.INDEX,"_doc", id); //查询ES GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT); if (getResponse.isExists()) { String sourceAsString = getResponse.getSourceAsString(); return Result.SUCCESS(getResponse.getSourceAsString()); } else { logger.error("没有找到该 id 的文档"); return Result.FAIL("没有找到该 id 的文档"); } } }
- 创建book索引类实体
package com.example.resthighclient.model; import lombok.Data; import java.io.Serializable; import java.util.Date; //通过这个注解,可以不用写gettersetter方法 @Data public class Book implements Serializable { private String id; private String title; private String content; private Integer userId; private Date createTime; }
- 使用postman工具,进行接口测试
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律