Spring boot 实现 Elasticsearch 动态创建索引
查找了很多方法都是通过Spring EL表达式实现 @Document(IndexName="#{demo.getIndexName}")
这种方式的问题在于没法解决数据库里生成的序号,例如我希望通过公司ID生成索引编号。后来在外网上找到一个大佬提出的解决方案,这位大佬把两种方案都实现了一遍。
通过entityId自定义index
Use an index name defined by the entity to store data in Spring Data Elasticsearch 4.0
通过SpEL动态生成index
How to provide a dynamic index name in Spring Data Elasticsearch using SpEL
我这里按照entity的方式实现了需求
elasticsearch 版本7.17.3
springboot版本2.7.1
Bean
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
@Document(indexName = ElasticSearchIndices.ES_INDEX_TROUBLES_COMPANY+"_*",createIndex = false)
public class CompanyTroubleshootingBean implements Serializable {private static final long serialVersionUID = 1L;@Id@JsonFormat(shape = JsonFormat.Shape.STRING)@JsonSerialize(using = ToStringSerializer.class)@Field(type = FieldType.Keyword , store = true)private Long id;@Field(type = FieldType.Text, analyzer = "ik_smart")private String content;@Field(type = FieldType.Text, analyzer = "ik_smart")private String searchKeyword;@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")private String contentMaxWord;@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")private String searchKeywordMaxWord;private Integer useCounts;//也是内容 这个内容不能分词查询@Field(type = FieldType.Keyword)private String keywordContent;@Field(type = FieldType.Keyword)private Integer catalogId;public String getContentMaxWord() {return content;}//私有化set方法,让该属性只读private void setContentMaxWord(String contentMaxWord) {this.content = contentMaxWord;}public String getSearchKeywordMaxWord() {return searchKeyword;}//私有化set方法,让该属性只读private void setSearchKeywordMaxWord(String searchKeywordMaxWord) {this.searchKeyword = searchKeywordMaxWord;}/*** 公司ID*/private Integer companyId;/*** 平台的解决方案ID*/@JsonFormat(shape = JsonFormat.Shape.STRING)@JsonSerialize(using = ToStringSerializer.class)private Long platformTroubleshootingId;}
接口
//相当于重新定义了一个repository
public interface CompanyTroubleshootElasticRepository<T> {<S extends T> S save(S entity);<S extends T> Iterable<S> save(Iterable<S> entities);
}
实现类
package online.ejiang.service.impl.troubleshooting;import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import online.ejiang.enums.ElasticSearchIndices;
import online.ejiang.pojo.elasticsearch.CompanyTroubleshootingBean;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;import java.util.concurrent.ConcurrentHashMap;/*** <p>* 公司故障排除及定价 服务实现类** </p>clo** @author Phil* @since 2020-07-22*/
@Service
@Slf4j
@RequiredArgsConstructor
public class CompanyTroubleshootingRepositoryImpl implements CompanyTroubleshootElasticRepository<CompanyTroubleshootingBean> {private final ElasticsearchOperations operations;@Nullableprivate Document mapping;@Overridepublic <S extends CompanyTroubleshootingBean> S save(S entity) {IndexCoordinates indexCoordinates = getIndexCoordinates(entity);S saved = operations.save(entity, indexCoordinates);operations.indexOps(indexCoordinates).refresh();return saved;}@Overridepublic <S extends CompanyTroubleshootingBean> Iterable<S> save(Iterable<S> entities) {if (entities != null && entities.iterator().hasNext()) {IndexCoordinates indexCoordinates = getIndexCoordinates(entities.iterator().next());Iterable<S> saved = operations.save(entities, indexCoordinates);operations.indexOps(indexCoordinates).refresh();return saved;}return null;}@NonNullprivate <S extends CompanyTroubleshootingBean> IndexCoordinates getIndexCoordinates(S entity) {String indexName = ElasticSearchIndices.ES_INDEX_TROUBLES_COMPANY + "_" + entity.getCompanyId();//把单实例的Map变成每次调用都初始化,解决重新同步时需要重启服务器的问题。ConcurrentHashMap<String, IndexCoordinates> knownIndexCoordinates = new ConcurrentHashMap<>();return knownIndexCoordinates.computeIfAbsent(indexName, i -> {IndexCoordinates indexCoordinates = IndexCoordinates.of(i);IndexOperations indexOps = operations.indexOps(indexCoordinates);if (!indexOps.exists()) {indexOps.create();if (mapping == null) {mapping = indexOps.createMapping(CompanyTroubleshootingBean.class);}indexOps.putMapping(mapping);}return indexCoordinates;});}
}
调用
do {IPage<CompanyTroubleshootingBean> beanPage = this.pageByCustom(new MyPage<>(index, 800), companyId);pages = beanPage.getPages();Iterable<CompanyTroubleshootingBean> saved = companyTroubleshootElasticRepository.save(beanPage.getRecords());if (saved != null && saved.iterator().hasNext()) {index++;} else {break;}} while (index <= pages);
Spring boot 实现 Elasticsearch 动态创建索引相关推荐
- Spring Boot整合elasticsearch实现全文检索
文章目录 1.引入 1.1 Luence 1.2 Solr 1.3 ElasticSearch 2. ElasticSearch安装 2.1 云服务器安装 2.1.1. docker安装 2.1.2 ...
- Elasticsearch学习(3) spring boot整合Elasticsearch的原生方式
前面我们已经介绍了spring boot整合Elasticsearch的jpa方式,这种方式虽然简便,但是依旧无法解决我们较为复杂的业务,所以原生的实现方式学习能够解决这些问题,而原生的学习方式也是E ...
- 第 4-8 课:Spring Boot 集成 ElasticSearch
ElasticSearch 是⼀个开源的搜索引擎,建⽴在⼀个全⽂搜索引擎库 Apache Lucene™ 基础之上. Lucene 可以说是当下最先进.⾼性能.全功能的搜索引擎库--⽆论是开源还是私有 ...
- Elasticsearch实战篇——Spring Boot整合ElasticSearch
2019独角兽企业重金招聘Python工程师标准>>> 当前Spring Boot很是流行,包括我自己,也是在用Spring Boot集成其他框架进行项目开发,所以这一节,我们一起来 ...
- (转)Spring Boot通过ImportBeanDefinitionRegistrar动态注入Bean
转自: Spring Boot通过ImportBeanDefinitionRegistrar动态注入Bean - 掘金在阅读SpringBoot源码时,看到SpringBoot中大量使用ImportB ...
- Elasticsearch如何创建索引,添加,删除,更新文档
文章目录 准备工作 检查 es 及 Kibana 是否运行正常 创建索引及文档 创建文档相关知识点 mulit-field 字段 关于两个type的解释 关于两个keyword的解释 mulit-fi ...
- ElasticSearch实战篇 - Spring Boot 整合 ElasticSearch
点击上方 Java后端,选择 设为星标 优质文章,及时送达 作者:冯文议 链接:segmentfault.com/a/1190000018625101 当前Spring Boot很是流行,包括我自己, ...
- Spring Boot 入门之登录创建
Spring Boot 入门之登录创建 一.在IDEA中创建一个springboot项目 1.使用Spring Initializr创建项目 2.选定Developer Tools中的Spring B ...
- Spring Boot集成Quartz动态实现数据库任务
1. Quartz简介 1.1. 什么是Quartz Quartz是一个开源的任务调度框架.作用是基于定时.定期的策略来执行任务. 它是OpenSymphony开源组织在Job scheduling领 ...
最新文章
- 人工智能在网络贷款中鲜为人知的事
- Lua学习笔记之数字
- gre biochemistry_【备考精选】2020年11月6日GRE写作Issue预测分享
- linux让脚本在指定时间运行程序,如何限制Linux命令程序运行的时间
- DVWA暴力破解(Brute Force)——全等级(Low,Medium,High,lmpossible)精讲
- 火出边际的Serverless,你居然还不了解?
- java接口回调测试
- Docker-服务安装
- python序列化-复习
- 自己做的一个漫画下载器
- 存储数据恢复案例_磁盘阵列数据恢复_raid5磁盘掉线数据恢复方法
- Android关闭输入法
- 王者荣耀服务器维护5月22,王者荣耀5月22日更新维护公告 更新内容汇总
- 巴西龟饲养日志----春日野采
- jQuery中的end()的用法与定义
- STM32 系统配置的时钟获取方式
- 终焉誓约怎么用电脑玩 终焉誓约模拟器玩法教程
- 中国女足,中国女垒,中国女排,舒米,让我欢喜让我忧
- 【娇娘内核】完整解密
- 再思考如何正确的致富