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既然無法通過注解動態修改名稱只能通過修改源碼解決了。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM