spring elasticsearch 动态索引
开发过程中数据量太大可能会每天生产一个新的索引SpringElasticsearch本身是面向对象,接口化的方式封装的代码所以一个对象创建时就已经无法改变只能修改源码。
这是下载源码: https://github.com/spring-projects/spring-data-elasticsearch/releases/tag/1.2.0.RELEASE。spring elasticsearch版本1.2.0,ES版本1.5.1。
导入源码到Eclipse在package org.springframework.data.elasticsearch.core.mapping;包下找到SimpleElasticsearchPersistentEntity.java代码,这个Java文件就不用多说了看源码也能看出来这是将我们创建的对象通过注解转换成Es的Index既然无法通过注解动态修改名称只能通过修改源码解决了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public SimpleElasticsearchPersistentEntity(TypeInformation<T> typeInformation) { super(typeInformation); this .context = new StandardEvaluationContext(); this .parser = new SpelExpressionParser(); Class<T> clazz = typeInformation.getType(); if (clazz.isAnnotationPresent(Document. class )) { Document document = clazz.getAnnotation(Document. class ); Assert.hasText(document.indexName(), " Unknown indexName. Make sure the indexName is defined. e.g @Document(indexName=\"foo\")" ); SimpleDateFormat dateFormat= new SimpleDateFormat( "yyyy-MM-dd" ); this .indexName = typeInformation.getType().getAnnotation(Document. class ).indexName()+dateFormat.format( new Date()); this .indexType = hasText(document.type()) ? document.type() : clazz.getSimpleName().toLowerCase(Locale.ENGLISH); this .shards = typeInformation.getType().getAnnotation(Document. class ).shards(); this .replicas = typeInformation.getType().getAnnotation(Document. class ).replicas(); this .refreshInterval = typeInformation.getType().getAnnotation(Document. class ).refreshInterval(); this .indexStoreType = typeInformation.getType().getAnnotation(Document. class ).indexStoreType(); } if (clazz.isAnnotationPresent(Setting. class )) { this .settingPath = typeInformation.getType().getAnnotation(Setting. class ).settingPath(); } } |
修改的代码非常简单二行。
1 2 | SimpleDateFormat dateFormat= new SimpleDateFormat( "yyyy-MM-dd" ); this .indexName = typeInformation.getType().getAnnotation(Document. class ).indexName()+dateFormat.format( new Date()); |
修改后Index名称后面就带上了当前日期了在ES添加数据那块的配置对上就行。重新打包 mvn package -DskipTests 替换掉原jar包。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)