Springboot 操作Elasticsearch 方式一 【spring-data-elasticsearch】
博主的环境是windows+elasticsearch6.7.1+kibana 6.7.1
{ "name" : "TDo83fR", "cluster_name" : "elasticsearch", "cluster_uuid" : "4-RI-qcBR46U9FtwxgEJ8g", "version" : { "number" : "6.7.1", "build_flavor" : "oss", "build_type" : "zip", "build_hash" : "2f32220", "build_date" : "2019-04-02T15:59:27.961366Z", "build_snapshot" : false, "lucene_version" : "7.7.0", "minimum_wire_compatibility_version" : "5.6.0", "minimum_index_compatibility_version" : "5.0.0" }, "tagline" : "You Know, for Search" }
- 添加ES依赖,不同版本springboot与ES环境依赖版本不同
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>elasticsearch</artifactId> <version>0.0.1-SNAPSHOT</version> <name>elasticsearch</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.5.RELEASE</version> <relativePath/> </parent> <dependencies> <!--引入ES--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-elasticsearch</artifactId> <!-- <version>3.1.21.RELEASE</version>--> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <!-- SLf4j 日志记录--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> <version>1.18.12</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.54</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
- 定义Article类
package com.example.elasticsearch.model; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import java.io.Serializable; import java.util.Date; //通过这个注解,可以不用写gettersetter方法,有时不好用 @Data @Document(indexName = "article",type = "_doc") public class Article implements Serializable { // 必须指定一个id @Id private String id; private String title; private String content; private Integer userId; private Date createTime; }
- 创建连接配置类ElasticsearchConfig
package com.example.elasticsearch.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.client.TransportClientFactoryBean; @Configuration public class ElasticsearchConfig { @Bean TransportClientFactoryBean client() { TransportClientFactoryBean bean=new TransportClientFactoryBean(); bean.setClusterName("elasticsearch");//默认为:elasticsearch bean.setClusterNodes("127.0.0.1:9300");//http连接9200,客户端方式9300 return bean; } }
- 创建ArticleRepository接口,实现ElasticsearchRepository接口
package com.example.elasticsearch.service; import com.example.elasticsearch.model.Article; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; @Repository public interface ArticleRepository extends ElasticsearchRepository<Article,String> { }
- 测试接口ArticleController类
package com.example.elasticsearch.controller; import com.example.elasticsearch.model.Article; import com.example.elasticsearch.response.Result; import com.example.elasticsearch.service.ArticleRepository; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.index.query.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @RestController @RequestMapping("/article") @Slf4j public class ArticleController { private final static Logger logger = LoggerFactory.getLogger(ArticleController.class); @Autowired private ArticleRepository articleRepository; // @Autowired // private ElasticsearchRestTemplate elasticsearchRestTemplate; //查询 // @Autowired // private ElasticsearchOperations elasticsearchOperations; //查询数据 @GetMapping("{id}") public Result findById(@PathVariable String id) { Optional<Article> article = articleRepository.findById(id); return Result.SUCCESS(article); } //删除数据 @DeleteMapping("{id}") public Result delete(@PathVariable String id) { // articleRepository.deleteAll(); articleRepository.deleteById(id); return Result.SUCCESS("删除成功"); } //保存数据 @PostMapping("save") public Result save(@RequestBody Article article) { if (article == null || StringUtils.isEmpty(article.getTitle())) { return Result.FAIL("标题不能为空"); } else if (StringUtils.isEmpty(article.getContent())) { return Result.FAIL("内容不能为空"); } article.setCreateTime(new Date()); Article a = articleRepository.save(article); if (a.getId() != null) return Result.SUCCESS("保存成功"); else return Result.FAIL("保存失败"); } @GetMapping("list") public Result list(@RequestParam(name = "pageLimit", defaultValue = "10") Integer pageLimit, @RequestParam(name = "pageCurrent", defaultValue = "1") Integer pageCurrent) { try { // 分页参数 Pageable pageable = PageRequest.of(pageCurrent-1,pageLimit); // QueryStringQueryBuilder builder = new QueryStringQueryBuilder(""); // SearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(builder).build(); // System.out.println("查询的语句:" + searchQuery.getQuery().toString()); Iterable<Article> articles = articleRepository.findAll(pageable);//(searchQuery); return Result.SUCCESS(articles); } catch (Exception ex) { logger.error(ex.getMessage()); } return Result.FAIL(); } }
- 通过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 绘制太阳,地球,月球 运作规律