轉載自:https://www.cnblogs.com/deepSleeping/p/11976262.html
需求:某實例需要按照月份來維護,所以之前的“寫死”索引的方式當然不行了。通過百度和看SpringDataElasticSearch官方文檔,最后解決了這個問題。
關鍵技術點: Spel表達式 (通過調用方法來獲取新的索引名,方法內處理新索引名的生成邏輯)
實體類部分代碼:
從表達式中可以看出:esConfig 是一個bean,調用了getXX方法。
@Document(indexName = "#{esConfig.getApiCallIndexName()}") public class ApiCallRecord { /** * 平台流水號 */ @Id @Field(type = FieldType.Keyword) private String transId; 。。。。。。 }
動態索引Bean代碼:
將改類注冊成Bean,名稱為“esConfig”,其中apiCallIndexNamePrefix,是索引的前綴(為了通用,讓它從配置文件取,如果沒有那么就設置默認值“api_call_rec_”),方法中的邏輯就是生成邏輯,這樣就能夠生成api_call_rec_yyyy_MM這樣的索引了。
@Component(value = "esConfig") public class ElasticSearchConfiguration { @Value("${esConfig.apiCallIndexName:api_call_rec_}") private String apiCallIndexNamePrefix; public String getApiCallIndexName() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy_MM"); return apiCallIndexNamePrefix + LocalDateTime.now().format(formatter); } }
動態 生成索引的源碼分析: