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包。

posted @   Jachs  阅读(5404)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示
人生而自由,却无往不在枷锁中。