SpringBoot+Elasticsearch按日期实现动态创建索引(分表)
创始人
2024-05-26 07:51:56
0
😊 @ 作者: 一恍过去 💖 @ 主页: https://blog.csdn.net/zhuocailing3390 🎊 @ 社区: Java技术栈交流 🎉 @ 主题: SpringBoot+Elasticsearch按日期实现动态创建索引(分表) ⏱️ @ 创作时间: 2023年02月19日

目录

  • 前言
  • 1、创建动态索引配置文件
  • 2、创建实体
  • 3、Repository对象
  • 4、Controller对象

前言

SpringBoot+Elasticsearch,通过@Document注解,利用EL表达式指定到配置文件,实现动态生成IndexName值,比如:

@Document(indexName = "product_#{@esIndex}")

1、创建动态索引配置文件

在配置文件中按照yyyy_MM_dd格式返回索引值的后缀,并且通过定时任务对索引值实现更新操作,定时任务是通过重建Bean对象实现对esIndex值进行更新。

重建Bean原因:Bean默认只有在服务启动时加载,若需动态改变Bean就要先销毁这个Bean之后再重新加载。


@Configuration
public class EsIndexConfig {@Resourceprivate ApplicationContext applicationContext;@Resourceprivate ElasticsearchRestTemplate elasticsearchRestTemplate;@Bean(name = "esIndex")public static String esIndex() {// 此处模拟按日期创建索引// 由于方便测试,索引直接返回时间戳,作为索引名称,时间可以为yyyy-MM-ddSimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");String date = sdf.format(new Date());System.out.println(date);date = System.currentTimeMillis() / 1000 + "";System.out.println("date:" + date);return date;}// 每天0点@Scheduled(cron = "0 0 0 * * ?")public void updateEsIndex() {DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();// 销毁指定实例defaultListableBeanFactory.destroySingleton("esIndex");String index = EsIndexConfig.esIndex();// 重新注册defaultListableBeanFactory.registerSingleton("esIndex", index);// 对索引进行一次手动创建(因为自动创建会丢失shards参数)IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(ProductEntity.class);if (!indexOperations.exists()) {indexOperations.create();}}
}

其他做法:
也可以不通过定时任务更新索引值,可以在操作save方法前,判断索引是否存在,如果不存在再进行重建Bean更新索引值,如下实例:

IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(ProductEntity.class);if (!indexOperations.exists()) {索引不存在,则重建Bean更新索引值}

2、创建实体

创建的实体类,需要关闭自动创建index属性(createIndex = false),通过配置文件来创建索引值,原因:如果开启自动索引,在项目启动时的第一个索引会完整创建成功,但是后续通过定时任务创建的索引会确实配置的shards、replicas参数

@Document(indexName = "product_#{@esIndex}", createIndex = false, shards = 3, replicas = 2)
@Data
public class ProductEntity implements Serializable {@Idprivate String id;/*** 文本类型,使用ik分词器*/@Field(type = FieldType.Text, analyzer = "ik_max_word")private String name;/*** 价格*/@Field(type = FieldType.Double)private BigDecimal money;/*** 时间戳*/@Field(type = FieldType.Long)private Long time;/*** 颜色*/@Field(type = FieldType.Keyword)private String color;
}

3、Repository对象

public interface ProductRepository extends ElasticsearchRepository {}

4、Controller对象

测试时,可以将索引动态更新的定时任务时间设置为一分钟,并且返回的索引值由yyyy_MM_dd修改为一个随机数;调用save方法后,过一分钟后再次进行调用,通过head/kibana观察是否生成了新的索引。

@RestController
@RequestMapping("es")
@Slf4j
public class ProductController {@Resourceprivate ProductRepository productRepository;@PostMappingpublic void save() {String[] colors = {"red", "purple", "blue"};String[] name = {"手机", "电脑", "微波炉", "电视"};// 新增列表数据List testList = new ArrayList<>();long sys = System.currentTimeMillis();for (int i = 0; i < 10; i++) {// 模拟随机数double random = Math.random() * 1000;ProductEntity productEntity = new ProductEntity();productEntity.setId(i + "");productEntity.setName(name[i % 4]);productEntity.setMoney(new BigDecimal(random));productEntity.setTime(sys + i % 3);productEntity.setColor(colors[i % 3]);testList.add(productEntity);}// 新增成功后,在head或者kibana中就可以看到相应数据,如果save时数据Id存在则更新操作// 批量新增productRepository.saveAll(testList);// 单个新增ProductEntity productEntity = testList.get(9);productEntity.setId("11");productRepository.save(productEntity);}
}

相关内容

热门资讯

【NI Multisim 14...   目录 序言 一、工具栏 🍊1.“标准”工具栏 🍊 2.视图工具...
银河麒麟V10SP1高级服务器... 银河麒麟高级服务器操作系统简介: 银河麒麟高级服务器操作系统V10是针对企业级关键业务...
不能访问光猫的的管理页面 光猫是现代家庭宽带网络的重要组成部分,它可以提供高速稳定的网络连接。但是,有时候我们会遇到不能访问光...
AWSECS:访问外部网络时出... 如果您在AWS ECS中部署了应用程序,并且该应用程序需要访问外部网络,但是无法正常访问,可能是因为...
Android|无法访问或保存... 这个问题可能是由于权限设置不正确导致的。您需要在应用程序清单文件中添加以下代码来请求适当的权限:此外...
北信源内网安全管理卸载 北信源内网安全管理是一款网络安全管理软件,主要用于保护内网安全。在日常使用过程中,卸载该软件是一种常...
AWSElasticBeans... 在Dockerfile中手动配置nginx反向代理。例如,在Dockerfile中添加以下代码:FR...
AsusVivobook无法开... 首先,我们可以尝试重置BIOS(Basic Input/Output System)来解决这个问题。...
ASM贪吃蛇游戏-解决错误的问... 要解决ASM贪吃蛇游戏中的错误问题,你可以按照以下步骤进行:首先,确定错误的具体表现和问题所在。在贪...
月入8000+的steam搬砖... 大家好,我是阿阳 今天要给大家介绍的是 steam 游戏搬砖项目,目前...