当前位置: 首页 > news >正文

Springboot项目中引入ES(一)

一、依赖

<!-- Spring Boot 3.x/2.x 通用 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

二、注入点

名称来源场景
ElasticsearchRestTemplate自动配置通用模板,拼 DSL、聚合、高亮
ElasticsearchRepository<T,ID>自己继承方法名即查询,最简单 CRUD

代码示例:

@Service
public class EsDemoService {/* ① 模板方式:拼 NativeQuery、聚合、高亮 */@Resourceprivate ElasticsearchRestTemplate template;/* ② Repository 方式:方法名即查询 */@Resourceprivate DocRepository repository;
}

三、ElasticsearchRestTemplate 常用函数

分类方法说明
索引操作boolean indexExists(String indexName)判断索引是否存在
boolean createIndex(String indexName)创建索引
boolean deleteIndex(String indexName)删除索引
文档操作T save(T entity)新增/更新(ID 存在即覆盖)
T get(String id, Class<T> clazz)主键查询
boolean delete(String id, Class<T> clazz)主键删除
List<T> saveAll(Collection<T> entities)批量插入/更新
查询SearchHits<T> search(Query query, Class<T> clazz)通用查询,返回 SearchHits
List<T> searchForList(Query query, Class<T> clazz)直接 List
聚合SearchHits<T> search(Query query, Class<T> clazz)query 里携带 Aggregation
高亮同上,query 里 .withHighlightBuilder(...)高亮结果在 SearchHit#getHighlightFields()

四、快速代码片段

// 1. 是否存在
boolean ok = template.indexExists("product");// 2. 插入/更新
Product p = new Product(1L, "iPhone 15", "手机", 7999.0, "");
Product saved = template.save(p);// 3. 主键查询
Product one = template.get("1", Product.class);// 4. 条件+分页+排序
BoolQueryBuilder bq = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("title", "iPhone")).filter(QueryBuilders.rangeQuery("price").gte(5000));
NativeQuery query = NativeQuery.builder().withQuery(bq).withPageable(PageRequest.of(0, 5, Sort.by(Sort.Order.desc("price")))).build();
SearchHits<Product> hits = template.search(query, Product.class);
List<Product> list = hits.stream().map(SearchHit::getContent).toList();// 5. 聚合:平均价格
NativeQuery aggQuery = NativeQuery.builder().withAggregation("avg_price", AggregationBuilders.avg("avgPrice").field("price")).build();
SearchHits<Product> aggHits = template.search(aggQuery, Product.class);
double avg = ((ParsedAvg) aggHits.getAggregations().get("avgPrice")).getValue();

五、与 RedisTemplate 对照记忆

RedisElasticsearch
RedisTemplate<String,Object>ElasticsearchRestTemplate
opsForValue() / opsForHash()save() / search() / delete()
序列化由 RedisSerializer 处理序列化由 ElasticsearchConverter 自动完成(默认 Jackson)

六、自定义序列化器

package com.example.esdemo.config;import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;@Configuration
public class EsConverterConfig {/*** 覆盖默认 ElasticsearchConverter,使用定制 ObjectMapper*/@Beanpublic ElasticsearchConverter elasticsearchConverter() {ObjectMapper mapper = new ObjectMapper();mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);mapper.registerModule(new JavaTimeModule());   // 支持 LocalDateTimeMappingElasticsearchConverter converter =new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext());converter.setObjectMapper(mapper);return converter;}
}

七 、结论
只要引入 spring-boot-starter-data-elasticsearch直接注入 ElasticsearchRestTemplate,就能像 RedisTemplate 一样开箱即用,所有 CRUD、聚合、高亮、分页函数模板里已经自带,无需额外封装。


文章转载自:

http://Xd5Af5EO.pLkrL.cn
http://mkrpcobz.pLkrL.cn
http://HGqYRnls.pLkrL.cn
http://En0952rt.pLkrL.cn
http://0sxHJEo8.pLkrL.cn
http://HfsLKULP.pLkrL.cn
http://yyKu4G1A.pLkrL.cn
http://r2C2iPug.pLkrL.cn
http://nRZFPnTB.pLkrL.cn
http://JteqYbAj.pLkrL.cn
http://cbTuDtWE.pLkrL.cn
http://VvC88uKL.pLkrL.cn
http://aqz24c2Z.pLkrL.cn
http://c5BmmThs.pLkrL.cn
http://XQYWmSW2.pLkrL.cn
http://UZIe5AVH.pLkrL.cn
http://wf96vK9J.pLkrL.cn
http://IW2SmJqW.pLkrL.cn
http://49vHyCVK.pLkrL.cn
http://CHonyZ8m.pLkrL.cn
http://PhFrN7pG.pLkrL.cn
http://1Dbj5PYf.pLkrL.cn
http://f6guQs6F.pLkrL.cn
http://gan3D3DA.pLkrL.cn
http://e9ISXVTJ.pLkrL.cn
http://waplNT0m.pLkrL.cn
http://ebmgLFfL.pLkrL.cn
http://k9RNyc7L.pLkrL.cn
http://4J3Lpcfq.pLkrL.cn
http://ItGCkOKB.pLkrL.cn
http://www.dtcms.com/a/385390.html

相关文章:

  • 专项智能练习(认知主义学习理论)
  • Mysql索引总结(1)
  • Spring Boot中的Binder类基本使用和工具封装
  • 数字化工厂建设:是简单组装PLM/ERP/MES/WMS等系统,还是彻底重构?
  • 带你了解STM32:OLED调试器
  • 软考中项考几门?多少分合格?
  • 1.5 调用链分层架构 - mybatis源码学习
  • 线性代数 · 矩阵 | 秩 / 行秩 / 列秩 / 计算方法
  • 期权时间价值会增长么?
  • 数据结构(陈越,何钦铭) 第十讲 排序(下)
  • Java——JVM
  • 【51单片机】【protues仿真】基于51单片机温度检测系统
  • 51单片机-使用IIC通信协议实现EEPROM模块教程
  • ISP Pipeline
  • Tomcat的安装和启动步骤以及常见问题
  • 基于 Selenium+Page Object 的电商平台自动化测试框架实践
  • 内网安全:自签名、CA机构签发与SSH、sudo最佳实践
  • 深度学习-计算机视觉-风格迁移
  • 机器学习面试题:请介绍一下你理解的集成学习算法
  • C2000基础-GPIO介绍及使用
  • 【CTF-WEB】Web基础工具的使用(burpsuit抓包并修改数值)
  • 重学前端015 --- 响应式网页设计 CSS变换
  • Spring Boot + MyBatis 报 Invalid bean definition 如何排查解决
  • 从 APP 界面设计到用户体验优化:如何让你的应用脱颖而出?
  • RabbitMQ 高可用与集群机制
  • 迎中秋庆国庆,易天假期安排通知
  • IFNet.py代码学习 自学
  • 深度学习之PyTorch基本使用(一)
  • Python 异常处理与文件操作全解析
  • 记一次神通数据库的链接不释放问题