开发过程中数据量太大可能会每天生产一个新的索引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既然无法通过注解动态修改名称只能通过修改源码解决了。
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(); } }
修改的代码非常简单二行。
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包。